Node.js 阻塞和非阻塞
Node.js基于事件驱动的非阻塞I/O模型。本文讨论了在Node.js中阻塞和非阻塞的含义。
阻塞: 它指的是在当前操作完成之前阻塞进一步操作。阻塞方法是同步执行的。同步意味着程序按照代码的顺序执行,程序会等待调用的函数或操作返回。
示例: 以下示例使用 readFileSync() 函数来读取文件,并展示了Node.js中的阻塞。
index.js
const fs = require('fs');
const filepath = 'text.txt';
// Reads a file in a synchronous and blocking way
const data = fs.readFileSync(filepath, {encoding: 'utf8'});
// Prints the content of file
console.log(data);
// This section calculates the sum of numbers from 1 to 10
let sum = 0;
for(let i=1; i<=10; i++){
sum = sum + i;
}
// Prints the sum
console.log('Sum: ', sum);
使用以下命令运行 index.js 文件:
node index.js
输出:
This is from text file.
Sum: 55
非阻塞: 它指的是程序不会阻塞后续操作的执行。非阻塞方法是异步执行的。异步执行意味着程序不一定会逐行执行。程序调用函数后会继续执行下一个操作,而不等待函数返回。
示例: 下面的示例使用readFile()
函数来读取文件,并演示了Node.js中的非阻塞。
index.js
const fs = require('fs');
const filepath = 'text.txt';
// Reads a file in a asynchronous and non-blocking way
fs.readFile(filepath, {encoding: 'utf8'}, (err, data) => {
// Prints the content of file
console.log(data);
});
// This section calculates the sum of numbers from 1 to 10
let sum = 0;
for(let i=1; i<=10; i++){
sum = sum + i;
}
// Prints the sum
console.log('Sum: ', sum);
使用以下命令运行 index.js 文件:
node index.js
输出:
Sum: 55
This is from text file.
注意: 在非阻塞程序中,实际上会先打印出求和结果,然后才会打印文件的内容。这是因为程序不等待readFile()函数返回就继续执行下一个操作。当readFile()函数返回时,才会打印文件的内容。