【发布时间】:2018-12-23 01:40:07
【问题描述】:
我是 node.js 的新手,所以我试图理解 Promise 并等待 node.js。我想打印文件note.txt。
这是我的代码
var fs = require('fs');
fs.readFile('note.txt','utf8').then(contents => console.log(contents))
.catch(err => console.error(err));
当我运行上面的代码时。我收到以下错误。
fs.readFile('note.txt','utf8').then(contents => console.log(contents))
TypeError: Cannot read property 'then' of undefined
at Object.<anonymous> (/Applications/nodeApps/test/index.js:13:31)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
我为同样的事情尝试了另一种方法。
var fs = require('fs');
async function read_file(){
var file_data = await fs.readFile('note.txt','utf8');
return file_data;
}
console.log(read_file());
我得到以下错误
Promise { <pending> }
(node:6532) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
当我使用 --harmony 运行时,我得到了同样的错误。我不确定我的代码是否有错误或有什么问题。请帮我理解。
我的环境 节点版本:v8.9.0
node -p process.versions.v8: 6.1.534.46
【问题讨论】:
-
readFile根本不返回承诺(实际上它返回undefined,根据您得到的错误)。它只接受回调。 nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback 。然而,有第三方模块将原生 Node API 包装在 Promise 中。 -
@FelixKling Not just third party ones
-
@FelixKling Not at all.
-
@Bergi:啊,没有意识到他们已经添加了它,我以为他们还在努力。这些天谁可以跟上:P 不确定对实验性 API 的感觉如何:D
标签: node.js ecmascript-6