Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。 

进程

1.process.argv 用于获取当前进程信息
0--node.exe的目录
1--js文件的目录
2--第一个参数 process.argv.slice(2) 获取从第一个参数开始的参数

2.process.env 获取当前系统的环境变量 3.process.stdout.write('xxx') console.log('xxx') = process.stdout.write('xxx\n');
4.process.stdin.on('data',function(data){

   process.stdout.write(data);
})
//回车时触发

传统的java,.net遇到阻塞io时会创建新的线程来处理。 node内部实现其实也是多线程的,(通过线程池)
//
多线程都是‘假’的,对于一个cpu核心。创建线程需要时间,线程数量有限,cpu在不同线程间切换需要转换上下文,耗费时间
多线程的意义并不大(多核心cpu则可能会提升效率) node的主线程————事件队列与事件循环圈。


模块

exports的实现:

module是定义在.js文件中的对象

xxx.js

console.log(module)

....(打印出module对象)

module中有一个exports对象,可以向内添加属性和方法

(参考 https://www.cnblogs.com/wbxjiayou/p/5767632.html)


写一个require的实现:

function $require(id){

const fs = require('fs');

const path = require('path');

const filename = path.join(__dirname,id);

$require.cache = $require.cache || {};

if($require.cache[filename]){

return $require.cache[filename].exports;

}

const dirname = path.dirname(filename);

let code = fs.readFileSync(filename,'utf8');

let module = { id:filename,exports:{} };

let exports = module.exports;

code=`

(function($require,module,exports,__dirname,__filename){

${code}

})($require,module,exports,dirname,filename)

;`;

eval(code);

$require.cache[filename] = module;

return module.exports;

}

var m4 =  $require('../xx.js');

m4.say();

...

清空require中的缓存机制:

Object.keys(require.cache).forEach((key)=>{delete require.cache[key]});

内置模块:

path:处理文件路径。

fs:操作(CRUD)文件系统。

child_process:新建子线程。

util:提供一系列实用小工具。

http:提供http服务器功能。

url:用于解析URL。

querystring:解析URL中的查询字符串。

crypto:提供加密和解密功能。

..

包(Node package manager):

Buffer

:读取文件时没有指定编码默认读取的是一个Buffer(缓冲区)

缓冲区:内存中操作数据的容器。

为什么要有缓冲区?

早期JS擅长处理字符串,及HTML文档,不会接触到二进制的数据。

而在Node中操作数据,网络通信是完全没法以字符串的方式操作的,所以在Node中引入了一个二进制缓冲区的实现,Buffer

//readfile的方式确实是使用buffer,但是也是一次性读取

Stream:

读一点数据,处理一点点数据(读到有限长的buffer中,然后再读取出来,)

写一个歌词滚动效果的实现:

假定有一个xxx.lrc文件

方法1.用buffer的方式读入fs.readFile(pathxx,callback)

在回调函数中对buffer进行tostring转换,然后split掉'\n',对于数组中的每一行,用正则提取时间,然后settimeout按时间显示出来

(由于对每一行处理需要耗费几毫秒的时间,可以设置begin=new Date().getTime() 然后在后面的settimeout中设置新的new Date.getTime()-begin 减掉这个时间)

方法2.用stream的方式读入 var streamReader = fs.createReadStream(filename);

var data = '';

streamReader.on('data',function(chunk){  data+=chunk.tostring(); });

streamReader.on('end',function(){console.log(data);  };

在这里对data进行处理

方法3.使用readline模块,用stream的方式读入 var streamReader = fs.createReadStream(filename);

var rl = readline.createInterface({ input:streamReader });

var begin = new Date().getTime();

rl.on('line',(line)=>{....对line进行处理})

写文件

默认写入是覆盖 ,可以使用append追加

方法1.fs.writeFile(path,callback);

方法2.var streamwriter = fs.createWriteStream(path);

streamwriter.write('xxx',callback)        (以流的方式写入,防止在内存中读取过多)

其他文件api

检查文件、删除、重命名..

写一个目录树显示的实现:

思路:通过使用fs.readdirSync

//打印当前目录所有文件
const fs = require('fs');
const path = require('path');
var target = path.join(__dirname,'./');
function load(target,depth){
var prefix = new Array(depth+1).join('| ');
 
var dirinfo = fs.readdirSync(target);
 
var dirs = [];
var files = [];
dirinfo.forEach(info=>{
var stats = fs.statSync(path.join(target,info))
if(stats.isFile()){
 
files.push(info);
}else{
 
dirs.push(info);
}
});
 
dirs.forEach(dir=>{
console.log(`${prefix}├─${dir}`);
load(path.join(target,dir),depth+1);
});
var count = files.length;
files.forEach(file=>{
console.log(`${prefix}${--count?'├':'└'}─${file}`);
});
};
load(target,0);
 

网络框架

Express框架的核心是对http模块的再包装

var http = require("http");
var app = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello world!");
});

app.listen(3000, "localhost");
var express = require('express');
var app = express(); app.get('/', function (req, res) {
res.send('Hello world!');
}); app.listen(3000);
中间件(middleware)是处理HTTP请求的函数。

app.use(function(req,res,next){
 
if(req.url == '/')
{
res.end('Welcome to the homepage!\n');
}else{
next();
}
});
app.use(function(req,res,next){
if(req.url == '/about'){
res.writeHead(200,{'Content-Type':'text/plain'});
}else{
next();
}
});
app.use(function(req,res){
res.writeHead(404,{'Content-Type':'text/plain'});
res.end('404 Error!\n');
});
 
也可以这样写:(将地址写在第一个参数里,这样只有对这个地址的请求,才有相应的回应)
app.use("/home", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the homepage!\n");
}); app.use("/about", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the about page!\n");
}); app.use(function(request, response) {
response.writeHead(404, { "Content-Type": "text/plain" });
response.end("404 error!\n");
}); http.createServer(app).listen(1337); 还可以这样写(*是指所有的请求都要先通过这个中间件)
app.all("*", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
next();
}); app.get("/", function(request, response) {
response.end("Welcome to the homepage!");
}); app.get("/about", function(request, response) {
response.end("Welcome to the about page!");
}); app.get("*", function(request, response) {
response.end("404!");
});
 

Node笔记(1)的更多相关文章

  1. node笔记——gulp修改静态文件的名字

    cmd小技巧: 1.换到下级或同等级目录 D: 2.换到上级目录 cd.. node 包管理器小技巧[以gulp为例] npm install --save-dev gulp gulp-concat ...

  2. Node笔记五-进程、线程

    进程 -每一个正在运行的应用程序都称之为进程 -每一个应用程序都至少有一个进程 -进程是用来给应用程序提供一个运行的环境 -进程是操作系统为应用程序分配资源的一个单位线程 -用来执行应用程序中的代码 ...

  3. Node笔记四

    异步操作 -Node采用chrome v8 引擎处理javascript脚本 --v8最大特点就是单线程运行,一次只能运行一个任务 -Node大量采用异步操作 --任务不是马上执行,而是插在任务队列的 ...

  4. Node笔记三

    global --类似与客户端javascript运行环境中的window process --用于获取当前node进程信息,一般用于获取环境变量之类的信息 console --node中内置的con ...

  5. Node笔记二

    ### 安装包的方式安装 - 安装包下载链接: + Mac OSX: [darwin](http://npm.taobao.org/mirrors/node/v5.7.0/node-v5.7.0.pk ...

  6. Node笔记一

    什么是javascript? --脚本语言 --运行在浏览器中 --一般用来做客户端页面的交互 javascript运行环境 --运行在浏览器内核中的JS引擎 浏览器这种javascript可以做什么 ...

  7. node笔记

    基础入门可参考: <一起学 Node.js>—— https://github.com/nswbmw/N-blog 核心模块使用前需要引入   let fs=require('fs'); ...

  8. node笔记汇总

    项目依赖分两种,一个就是普通的项目依赖比如bootstrap,还用一种只是开发阶段需要用的,这种属于开发依赖比如gulp,开发依赖最终记录在devDependencies节点里面 -          ...

  9. Node笔记 - process.cwd() 和 __dirname 的区别

    process.cwd() 返回工作目录  __dirname 返回脚本所在的目录位置 单看概念觉得都差不多,有种似懂非懂的感觉,那么接下用一个简单易懂的例子来理解下这两者的区别,在此之前先看一个方法 ...

随机推荐

  1. 洛谷——P2038 无线网络发射器选址

    https://www.luogu.org/problem/show?pid=2038 题目描述 随着智能手机的日益普及,人们对无线网的需求日益增大.某城市决定对城市内的公共场所覆盖无线网. 假设该城 ...

  2. bootstrap-table 表头和内容对不齐

    问题: bootstrap-table.js 找到 BootstrapTable.prototype.resetView if (this.options.showHeader && ...

  3. spring-cloud-feign 使用@RequetParam报错QueryMap parameter must be a Map: class java.lang.String

    这里使用spring-cloud-start-feign: 1.2.2 REALEASE版本,依赖管理器版本是 Camden.SR2 出错的原因是@RequestParam的value为empty时, ...

  4. Linux文字分段裁剪命令cut(转)

    Linux cut命令用于显示每行从开头算起num1到num2的文字. 语法 cut [-bn] [file] cut [-c] [file] cut [-df] [file] 使用说明: cut命令 ...

  5. ruby for in 循环中改变i的值无效

    ruby for in 循环中改变i的值无效 for j in 1..5 puts "#{j}hehe" j = j + 2 #break end 在循环中,使用j = j + 2 ...

  6. 哈理工 oj 2122 旅行(map + 最短路dij算法)

    旅行 Time Limit: 1000 MS Memory Limit: 32768 K Total Submit: 18(6 users) Total Accepted: 3(3 users) Ra ...

  7. er图简单回顾

    实体对象:矩形 属性:椭圆 关系:菱形 一对一,一对多,多对一,多对多

  8. poj1179 区间dp(记忆化搜索写法)有巨坑!

    http://poj.org/problem?id=1179 Description Polygon is a game for one player that starts on a polygon ...

  9. luogu3690 【模板】 Link Cut Tree(动态树)

    题目大意 给定n个点以及每个点的权值,要你处理接下来的m个操作.操作有4种.操作从0到3编号.点从1到n编号.0.询问从x到y的路径上的点的权值的xor和.保证x到y是联通的.1.代表连接x到y,若x ...

  10. 局部变量,全局变量,extend,static

    main.c #include <stdio.h> #include "zs.h" /* 局部变量是定义在函数.代码块.函数形参列表.存储在栈中,从定义的那一行开始作用 ...