Nodejs Guides
Posted Merrys
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Nodejs Guides相关的知识,希望对你有一定的参考价值。
page3.Overview of Blocking vs Non-Blocking
This overview covers the difference between blocking and non-blocking calls in Node.js. This overview will refer to the event loop and libuv but no prior knowledge of those topics is required. Readers are assumed to have a basic understanding of the javascript language and Node.js callback pattern.
"I/O" refers primarily to interaction with the system‘s disk and network supported by libuv.
概述Nodejs中阻塞和非阻塞之间的区别。
***Blocking
Blocking is when the execution of additional JavaScript in the Node.js process must wait until a non-JavaScript operation completes. This happens because the event loop is unable to continue running JavaScript while a blocking operation is occurring.
阻塞指的是在Node.js进程中,必须等到非Javascript代码执行完毕,才执行Javascript代码。这是由javascript的执行机制引起的。
Synchronous methods in the Node.js standard library that use libuv are the most commonly used blocking operations. Native modules may also have blocking methods.
Nodejs标准库中使用(libuv)的同步方法大多数都是阻塞操作。本地模块也有阻塞方法。
All of the I/O methods in the Node.js standard library provide asynchronous versions, which are non-blocking, and accept callback functions. Some methods also have blocking counterparts, which have names that end with Sync
.
Node.js标准库中的所有的I/O方法都提供异步版本--非阻塞的---接受回调函数。有的方法同时也有同步版本---它们命名时带有Sync。
***Comparing Code
Blocking methods execute synchronously and non-blocking methods execute asynchronously.
阻塞方法同步执行,非阻塞方法异步执行。
example:
const fs = require(‘fs‘);
console.log("1");
const data = fs.readFileSync(‘./package.json‘); // blocks here until file is read
console.log("2");
fs.readFile(‘./package.json‘, (err, data) => {
console.log("5")
if (err) throw err;
});
console.log("4");
//1,2,4,5
The first example appears simpler than the second but has the disadvantage of the second line blocking the execution of any additional JavaScript until the entire file is read. Note that in the synchronous version if an error is thrown it will need to be caught or the process will crash. In the asynchronous version, it is up to the author to decide whether an error should throw as shown.
在同步方法中,error抛出后需被捕获,否则进程会崩溃。异步方法中,这取决于使用者是否要抛出error。
Let‘s expand our example a little bit:
const fs = require(‘fs‘); const data = fs.readFileSync(‘/file.md‘); // blocks here until file is read console.log(data); // moreWork(); will run after console.log
And here is a similar, but not equivalent asynchronous example:
const fs = require(‘fs‘); fs.readFile(‘/file.md‘, (err, data) => { if (err) throw err; console.log(data); }); // moreWork(); will run before console.log
In the first example above, console.log
will be called before moreWork()
. In the second example fs.readFile()
is non-blocking so JavaScript execution can continue and moreWork()
will be called first. The ability to run moreWork()
without waiting for the file read to complete is a key design choice that allows for higher throughput.
***Concurrency(并发) and Throughput
JavaScript execution in Node.js is single threaded, so concurrency refers to the event loop‘s capacity to execute JavaScript callback functions after completing other work. Any code that is expected to run in a concurrent manner must allow the event loop to continue running as non-JavaScript operations, like I/O, are occurring.
Node.js中的JavaScript执行是单线程的,因此并发指的是事件循环在完成其他工作后执行JavaScript回调函数的能力。任何期望以并发方式运行的代码都必须允许事件循环在非JavaScript操作(如I / O)正在发生时继续运行。
As an example, let‘s consider a case where each request to a web server takes 50ms to complete and 45ms of that 50ms is database I/O that can be done asynchronously. Choosing non-blocking asynchronous operations frees up that 45ms per request to handle other requests. This is a significant difference in capacity just by choosing to use non-blocking methods instead of blocking methods.
例如,一个需要50ms的server请求,其中45ms用来数据库的I/O操作----可以异步完成。选择非阻塞的异步操作节约了每次请求后都需要的45ms去处理其他的需求。这是使用非阻塞方法而不使用阻塞方法的性能上的巨大不同。
The event loop is different than models in many other languages where additional threads may be created to handle concurrent work.
在其他能创建多线程的语言里,事件循环机制是不同的。
***Dangers of Mixing Blocking and Non-Blocking Code
There are some patterns that should be avoided when dealing with I/O. Let‘s look at an example:
const fs = require(‘fs‘); fs.readFile(‘/file.md‘, (err, data) => { if (err) throw err; console.log(data); }); fs.unlinkSync(‘/file.md‘);
In the above example, fs.unlinkSync()
is likely to be run before fs.readFile()
, which would delete file.md
before it is actually read. A better way to write this that is completely non-blocking and guaranteed to execute in the correct order is:
const fs = require(‘fs‘); fs.readFile(‘/file.md‘, (readFileErr, data) => { if (readFileErr) throw readFileErr; console.log(data); fs.unlink(‘/file.md‘, (unlinkErr) => { if (unlinkErr) throw unlinkErr; }); });
The above places a non-blocking call to fs.unlink()
within the callback of fs.readFile()
which guarantees the correct order of operations.
page4.Debugging Guide
This guide will help you get started debugging your Node.js apps and scripts.
***Enable Inspector
NOTE: The --inspect
option and Inspector Protocol are experimental and may change.
NOTE:--inspect 指令和Inspector Protocol 还在试验阶段,可能会有改变。
When started with the --inspect switch, a Node.js process listens via WebSockets for diagnostic commands as defined by the Inspector Protocol, by default at host and port 127.0.0.1:9229. Each process is also assigned a unique UUID (e.g. 0f2c936f-b1cd-4ac9-aab3-f63b0f33d55e
).
当我们使用--inspect指令时,Node.js进程监控通过WebSockets由Inspector Protocol 定义的诊断指令,默认的主机和端口是127.0.01:9229.每个进程都会发出一个唯一的UUID。
Inspector clients must know and specify host address, port, and UUID to connect to the WebSocket interface. The full URL isws://127.0.0.1:9229/0f2c936f-b1cd-4ac9-aab3-f63b0f33d55e
, of course dependent on actual host and port and with the correct UUID for the instance.
for example:
node --inspect app3.js Debugger listening on port 9229. Warning: This is an experimental feature and could change at any time. To start debugging, open the following URL in Chrome: chrome-devtools://devtools/remote/serve_file/@60cd6e859b9f557d2312f5bf532f6aec5f284980/inspector.html?experiments=true&v8only=t rue&ws=127.0.0.1:9229/afd09ed8-84b6-48cd-9975-fe8b06473fbb
Haha,I still don‘t know how to debugger.
I may need a more time to practice and understand this part.
以上是关于Nodejs Guides的主要内容,如果未能解决你的问题,请参考以下文章
text https://nodejs.org/en/docs/guides/blocking-vs-non-blocking/