分类 Node.js相关 下的文章

关于 Node.js 的setImmediate, setTimeout, process.nextTick

要根据 Node.js 的event loop 来理解这些 setImmediate, setTimeout, process.nextTick

Node.js actually provides its own implementation of these methods. Timers integrate very closely with the system, and despite the fact that the API mirrors the browser API, there are some differences in implementation.

console.log("start of hello");

setImmediate(()=>{
    console.log("in setImmediate");
    setImmediate(()=>{
        console.log("in setImmediate's setImmediate"); //the 3rd loop
    });
});

setTimeout(()=>{
    console.log("in setTimeout");
    setImmediate(()=>{
        console.log("in setTimeout's setImmediate"); //2nd loop 
    });
}, 0);

process.nextTick(()=>{
    console.log("in nextTick"); //next event action
    process.nextTick(()=>{
        console.log("in nextTick's nextTick"); // next event action
    });
});

console.log("end of hello");

process.nextTick 是当前event action 处理完之后, 下一个会处理的action.

Node.js 文档

Node.js 使用event loop的并发模型 vs 其它语言的 多线程并发模型;
Node.js 的关键是 对于所有的非CPU 计算操作全部都使用异步的callback 模式;

基本语法

node [options] [V8 options] [script.js | -e "script" | -] [--] [arguments]
node inspect [script.js | -e "script" | <host>:<port>] …
node --v8-options

Node.js 对于 ES2015 Support
https://node.green/

Node.js 文档: https://nodejs.org/en/docs/

启用debug:
node --inspect hello.js
会打出如下:

chrome-devtools://devtools/remote/serve_file/@60cd6e859b9f557d2312f5bf532f6aec5f284980/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9229/6285270a-4795-40d7-992f-cfc452461144

然后打开9229端口:

http://localhost:9229/json/list

即便一开始没有启用 --inspect 参数, 启动之后, 还是可以通过发送 SIGUSR1 signal, 让它打开debuger (kill -l 查看全部signal)

Node.js is an event-based platform. This means that everything that happens in Node is the reaction to an event. A transaction passing through Node traverses a cascade of callbacks.

关于 Event Loop: link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop