node.js 如何修复此错误 TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51150956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to fix this error TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
提问by Thirupparan
I am a beginner to the nodejs. When I type the below, the code error occurs like this:
我是 nodejs 的初学者。当我输入以下内容时,代码错误如下:
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
TypeError [ERR_INVALID_CALLBACK]: 回调必须是一个函数
var fs = require('fs');
fs.readFile('readMe.txt', 'utf8', function (err, data) {
fs.writeFile('writeMe.txt', data);
});
回答by Wejd DAGHFOUS
Fs.writeFile() according to the documentation heretakes ( file, data[, options]and callback ) params so your code will be like this :
Fs.writeFile() 根据此处的文档采用(文件、数据[、选项]和回调)参数,因此您的代码将如下所示:
var fs = require('fs');
fs.readFile('readMe.txt', 'utf8', function (err, data) {
fs.writeFile('writeMe.txt', data, function(err, result) {
if(err) console.log('error', err);
});
});
回答by phuzi
fs.writeFile(...)requires a third (or fourth) parameter which is a callback function to be invoked when the operation completes. You should either provide a callback function or use fs.writeFileSync(...)
fs.writeFile(...)需要第三个(或第四个)参数,它是在操作完成时调用的回调函数。您应该提供回调函数或使用fs.writeFileSync(...)
See node fs docsfor more info.
有关更多信息,请参阅节点 fs 文档。
回答by Oscar Zhang
Since node 10, it is mandatory to pass a callback on fs.writefile()
从节点 10 开始,必须在上传递回调 fs.writefile()
Node.js documented the purpose for the change: https://github.com/nodejs/node/blob/master/doc/api/deprecations.md#dep0013-fs-asynchronous-function-without-callback
Node.js 记录了更改的目的:https: //github.com/nodejs/node/blob/master/doc/api/deprecations.md#dep0013-fs-asynchronous-function-without-callback
You could add an empty callback like this fs.writeFile('writeMe.txt', data, () => {})
你可以像这样添加一个空回调 fs.writeFile('writeMe.txt', data, () => {})
回答by Shashwat Gupta
you also use like this
你也这样用
var file2 = await fs.readFileSync("./Public/n2.jpeg")
回答by Jim Aho
This error hit me in the face when I was doing the following;
当我执行以下操作时,这个错误击中了我;
var hello = myfunction( callme() );
var hello = myfunction( callme() );
rather than
而不是
var hello = myfunction( callme );
var hello = myfunction( callme );

