面试题答案
一键面试非阻塞I/O与文件系统交互
在Node.js中,非阻塞I/O允许Node.js在执行I/O操作(如文件系统操作)时,不会阻塞主线程的执行。这是通过事件驱动和异步回调机制实现的。当一个非阻塞I/O操作(如读取或写入文件)开始时,Node.js不会等待操作完成,而是继续执行后续代码。当操作完成后,Node.js通过事件循环检测到操作完成,并执行相应的回调函数来处理结果。
fs.readFile在非阻塞模式下的使用及原理
使用示例
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
console.log('This is printed before the file reading is complete');
原理
- 调用fs.readFile:当调用
fs.readFile
时,Node.js将文件读取操作交给底层的操作系统I/O模块,同时主线程继续执行后续代码(即打印This is printed before the file reading is complete
)。 - 事件循环:Node.js的事件循环持续检查事件队列。当文件读取操作完成后,操作系统将完成信号放入事件队列。
- 回调执行:事件循环检测到文件读取完成的信号后,从事件队列中取出该事件,并将其对应的回调函数(即
(err, data) => {... }
)放入执行栈中执行。如果读取过程中发生错误,err
会被赋值,否则data
会包含文件内容。
fs.writeFile在非阻塞模式下的使用及原理
使用示例
const fs = require('fs');
const content = 'This is some text to write to the file';
fs.writeFile('newFile.txt', content, (err) => {
if (err) {
console.error(err);
return;
}
console.log('File written successfully');
});
console.log('This is printed before the file writing is complete');
原理
- 调用fs.writeFile:调用
fs.writeFile
时,Node.js将文件写入操作交给底层操作系统I/O模块,主线程继续执行后续代码(即打印This is printed before the file writing is complete
)。 - 事件循环:同样,事件循环持续检查事件队列。当文件写入操作完成后,操作系统将完成信号放入事件队列。
- 回调执行:事件循环检测到文件写入完成的信号后,取出该事件,并将对应的回调函数(即
(err) => {... }
)放入执行栈执行。如果写入过程中发生错误,err
会被赋值,否则说明文件写入成功。