用ES6读取文件 [英] reading file with ES6 promises
本文介绍了用ES6读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
let arr = [];
function getData(fileName, type) {
return fs.readFile(fileName,'utf8', (err, data) => {
if (err) throw err;
return new Promise(function(resolve, reject) {
for (let i = 0; i < data.length; i++) {
arr.push(data[i]);
}
resolve();
});
});
}
getData('./file.txt', 'sample').then((data) => {
console.log(data);
});
当我使用上面的代码并使用nodejs在命令行中运行它时,出现以下错误.
When I use above code and run it in command line using nodejs I get following error.
getData('./file.txt', 'sample').then((data) => {
^
TypeError: Cannot read property 'then' of undefined
我该如何解决?
推荐答案
您将希望将整个fs.readFile
调用包装在新的Promise
中,然后根据回调结果拒绝或解决承诺:
You'll want to wrap the entire fs.readFile
invocation inside a new Promise
, and then reject or resolve the promise depending on the callback result:
function getData(fileName, type) {
return new Promise(function(resolve, reject){
fs.readFile(fileName, type, (err, data) => {
err ? reject(err) : resolve(data);
});
});
}
[更新]从Node.js v10开始,您可以选择使用fs.promises.<API>
使用fs
模块的内置Promise实现.对于我们的readFile
示例,我们将更新解决方案以使用fs.promises
这样:
[UPDATE] As of Node.js v10, you can optionally use the built-in Promise implementations of the fs
module by using fs.promises.<API>
. In the case of our readFile
example, we would update our solution to use fs.promises
like this:
function getData(fileName, type) {
return fs.promises.readFile(fileName, {encoding: type});
}
这篇关于用ES6读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文