事件驱动学习; 很多东西,不同阶段再去听去看,会有不同收获,因为基础认知不同,才能理解到一些细节
三句basic 说明
- Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine.
- As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications.
- Almost no function in Node.js directly performs I/O, so the process never blocks except when the I/O is performed using synchronous methods of Node.js standard library.
usage
- web应用场景
- SSR-搜索引擎优化,首屏速度
- 前后端同构(PDF预览打印场景
1
2
3
4
5
6
7
8
9前后端同构
浏览器端 && nodejs端 => 同构代码
ReactDomServer.renderToString()
VueServerRenderer.renderToString()
R&V最大难题在于数据部分
同构的core
- 注重职责分离 - 构建工具(早期的 gulp,webpack,后面不用说了,奏是这个生态)
- Backend for Frontend(HTTP, RPC调用)
basic
global
__filename | __dirname
Err
EMFILE - Too many open files
Process
- argv
- env
- kill
- exit
- hrtime
- cpuUsage
- memoryUsage
Module
browser
- 脚本加载顺序
- 脚本之间逻辑调用,借助全局变量
commonJS
- 也影响了browser端
Doc
- http://nodejs.cn/api/process.html
Details
- process 对象是 EventEmitter 的实例
- doc
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'beforeExit' 事件#
中英对照
新增于: v0.11.12
当 Node.js 清空其事件循环并且没有额外的工作要安排时,则会触发 'beforeExit' 事件。 通常情况下,当没有工作要调度时,Node.js 进程会退出,但是注册在 'beforeExit' 事件上的监听器可以进行异步的调用,从而使 Node.js 进程继续。
调用监听器回调函数时将 process.exitCode 的值作为唯一的参数传入。
对于导致显式终止的条件,例如调用 process.exit() 或未捕获的异常,则不会触发 'beforeExit' 事件。
'beforeExit' 不应用作 'exit' 事件的替代,除非打算安排额外的工作。
import process from 'process';
process.on('beforeExit', (code) => {
console.log('Process beforeExit event with code: ', code);
});
process.on('exit', (code) => {
console.log('Process exit event with code: ', code);
});
console.log('This message is displayed first.');
// 打印:
// This message is displayed first.
// Process beforeExit event with code: 0
// Process exit event with code: 0
1 | 'exit' 事件# |
1 | - SIGINT P1990 Term Interrupt from keyboard |
recommend
chalk
- https://www.npmjs.com/package/chalk
- 调试时候可以用,这样比较显眼
网关
- https://mp.weixin.qq.com/s/nWKCX1INkP7uKGONzW7CPg
- 大规模 Node.js 网关的架构设计与工程实践
服务间接口调用
- consul 测试环境 ip+端口号
- cluster IP + 80 线上环境
- 没有用域名做代理,当然会存在cluster ip更换的问题,不过相对稳定
windows
系统属性里面的环境变量设置
node - test框架推荐
- ava这个框架
preventing-sql-injection-in-node-js
- https://stackoverflow.com/questions/15778572/preventing-sql-injection-in-node-js
- https://github.com/mysqljs/mysql#escaping-query-values
problems - BFF
cases
BFF
- Java服务提供数据 - RPC通信
- 模版渲染
- API服务 - restful(易读,快速启动,数据聚合劣势)- github的v3 API的实现
- API服务 - GraphQL(专注数据聚合,返回前端需要的)