NodeJs

Node.js是一个Javascript运行环境(runtime)。发布于2009年5月,由Ryan Dahl开发,实质是对Chrome V8引擎进行了封装。
Node.js 的包管理器 npm,是全球最大的开源库生态系统。
官网:https://nodejs.org

线程模型和事件循环

线程模型

Apache+Tomcat(6,7,8,9)运行

  1. req来袭
  2. thread应对
  3. req处理完后,thread释放

线程处理模式就是重复以上三个步骤,来处理来自客户端的各种请求,当有大量客户端的请求来袭时,服务器消耗的资源也会随之增加。

事件循环

Node.js服务运行

  1. 开一个事件等待循环(event-loop)
  2. req来袭
  3. 放入事件处理队列中,然后继续等待新的req请求
  4. req处理完成后,调用I/O,结束req(非阻塞调用)

事件循环处理模式中,线程不用等待req处理完后在进行下个req的处理,而是将所有的req请求放入到队列之中,然后采用非同步的方式,等待req处理完后再调用I/O资源,然后结束req。

命令

1
2
3
4
5
6
$ node
> console.log("Helo World.");
> .help
> .exit

$ node filename.js

非阻塞处理

  • 阻塞
1
2
3
4
5
var start = new Date().getTime();
while(new Date().getTime() < start + 3000);

// 3s后打印
console.log("hello world");
  • 非阻塞
1
2
3
4
// 程序一运行就打印world, 3s后打印hello
setTimeout(() => console.log("hello"), 3000)

console.log("world")

实现http服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const fs = require("fs");                  // 引入fs库(文件系统)
const http = require("http"); // 引入http库
const config = require("./config").config // 引入config

const server = http.createServer((req, resp) => {
// 拼接资源全路径
var filename = null;
if (req.url == "/") {
filename = "./page/index.html"
} else {
filename = "./page" + req.url;
}

// 读取资源, 并发送响应
fs.readFile(filename, "utf-8", function (err, data) {
resp.setHeader("Content-type", "text/html");

if (err) {
resp.statusCode = 404;
resp.end("not found!");
} else {
resp.statusCode = 200;
resp.end(data);
}
})
});

server.listen(config.port, config.hostname, () => {
console.log(`Server runing at http://${config.hostname}:${config.port}/`)
})

npm包管理工具

1
2
3
$ npm install moduleName		# 当前项目
$ npm install -g moduleName # 全局安装
$ npm install

nrm

NPM registry manager

1
2
3
$ npm install -g nrm	# 安装npm
$ nrm ls # 查看源
$ nrm use 源 # 切换下载源

ejs使用

“E” 代表 “effective”,即【高效】。EJS 是一套简单的模板语言,帮你利用普通的 JavaScript 代码生成 HTML 页面。EJS 没有如何组织内容的教条;也没有再造一套迭代和控制流语法;有的只是普通的 JavaScript 代码而已。

Nodejs操作MongoDB

Promise承诺

优点

  • 使用Promise可以解决回调地狱问题
  • Promise对象API简洁,操作简单

Promise常用API

实例方法:

  • then():得到异步任务的正确结果
  • catch():获取异常信息
  • finally():成功与否最终都会执行的方法

类方法

  • Promise.all():并发处理多个异步任务,所有任务都执行完成后,返回所有结果
  • Promise.race():并发处理多个异步任务,只要有一个任务完成就返回结果,并且只有这个返回的结果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 更新数据库操作
function updateDB(sql) {
let p = new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`${sql} update ok!`);
resolve(`${sql} ok!`);
}, 500);
});
return p; // 返回promise对象
}

updateDB("sql1")
.then(() => updateDB("sql2"))
.then(() => updateDB("sql3"))

let p1 = updateDB("sql1");
let p2 = updateDB("sql2");
let p3 = updateDB("sql3");

Promise.all([p1, p2, p3])
.then((res) => console.log(res));

Promise.race([p1, p2, p3])
.then((res) => console.log(res));

async/await

ES7引入的语法,方便进行异步操作

  • async关键字用于函数上,async函数的返回值是Promise对象
  • await关键字用于async函数中,用于获取异步请求的结果
1
2
3
4
5
6
7
8
async function updateAll() {
// 顺序执行这三个异步更新请求
let res1 = await updateDB("sql1");
let res2 = await updateDB("sql2");
let res3 = await updateDB("sql3");
console.log(res1 + res2 + res3);
}
updateAll();

 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×