面试题答案
一键面试const fs = require('fs');
const path = require('path');
function readFileContent(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(path.resolve(filePath), 'utf8', (err, data) => {
if (err) {
if (err.code === 'ENOENT') {
reject(new Error('文件路径不存在'));
} else {
reject(err);
}
} else {
resolve(data);
}
});
});
}
// 使用示例
readFileContent('test.txt')
.then(content => {
console.log(content);
})
.catch(err => {
console.error(err.message);
});
选择 fs.readFile
方式能保证高效的原因如下:
- 异步操作:
fs.readFile
是异步操作,不会阻塞 Node.js 事件循环,允许程序在读取文件的同时执行其他任务,提升整体效率。 - 缓冲区处理:它会将文件内容读取到缓冲区中,对于小文件可以一次性读入内存,避免多次 I/O 操作带来的开销。