index
module
- 为什么能在代码中使用全局变量require和exports以及module?
因为node把主代码用function包了起来 传入了这些入参哇!可以把 node 想象成一个 container
输入
- Readfile 与 createReadStream
后者可以自定义按 chunk 读入
输出
装npm的时候经常可以看见一闪而过的log 最后不会停留在输入框里
其实本质就是 this.stream 系列
ref: https://github.com/visionmedia/node-progress/blob/master/lib/node-progress.js
http
- 为什么http模块创建的HTTP服务器返回的响应是chunked传输方式的?
因为默认情况下,使用.writeHead方法写入响应头后,允许使用.write方法写入任意长度的响应体数据,并使用.end方法结束一个响应。由于响应体数据长度不确定,因此NodeJS自动在响应头里添加了Transfer-Encoding: chunked字段,并采用chunked传输方式。但是当响应体数据长度确定时,可使用.writeHead方法在响应头里加上Content-Length字段,这样做之后NodeJS就不会自动添加Transfer-Encoding字段和使用chunked传输方式。
Ref: https://nqdeng.github.io/7-days-nodejs/#4.2
eventLoop 相关
- nodejs的eventloop和浏览器的是否一样?
不一样。nodejs的eventloop由用C写的libuv(li:b uv)控制,因为异步通常涉及的是I/O操作
记住process.nextTick最靠前,在每个阶段中间都会检查(process.nextTick()是node早期版本无setImmediate时的产物,node作者推荐我们尽量使用setImmediate。);
immediate比timeOut:正常情况下不确定;I/O流程写immediate要提前执行
原文文档:https://nodejs.org/de/docs/guides/event-loop-timers-and-nexttick/
对应很好的讨论:https://cnodejs.org/topic/57d68794cb6f605d360105bf
cluster、worker 相关
cluster
- One process is launched on each CPU and can communicate via IPC. 其实就是一个单独的 nodejs 进程.
- Each process has it's own memory with it's own Node (v8) instance. Creating tons of them may create memory issues.
- 使用场景:Great for spawning many HTTP servers that share the same port b/c the ~~master~~ main process will multiplex the requests to the child processes.
- 使用方式:同
child_process.fork()
Worker threads
- One process total
- Creates multiple threads with each thread having one Node instance (one event loop, one JS engine). 所以实际上,是 v8 isolate 的.
- Shares memory with other threads (e.g.
SharedArrayBuffer
), 或通过 MessagePort 通信 - 使用场景:For CPU intensive/long-running tasks like processing data or accessing the file system. 但是 不要用来处理 io 哦(Workers (threads) are useful for performing CPU-intensive JavaScript operations. They do not help much with I/O-intensive work. The Node.js built-in asynchronous I/O operations are more efficient than Workers can be.--- e.g. 微服务间请求 因只用耗时 不用耗功 所以也属于 I/O 范畴)
process v.s. thread
常见的有以下几个误区:
-
process 和 thread 一定会提高效率 - 都是任务数>核数的情况下并发,否则并行。能多用核的情况下一定会提高效率,否则只是平均分配了时间。
-
老生常谈的,Nodejs 是多线程或单线程?- Precisely, Node.js runs JS code in a single thread, 但是 node.js 本身是 multithreaded.
-
cpu-intensive 使用 promise 是否可以 offload 掉?- 不可以。因为 i/o operations 有效率的本质是「make use of Node.js hidden libuv threads, which CPU-bound tasks do not」.
非常好的 refs: