how to fix this error TypeError [ERR_INVALID_CALLBACK]: Callback must be a function

北慕城南 提交于 2020-02-01 09:54:34

问题


I am a beginner to the nodejs. When I type the below, the code error occurs like this:

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function

var fs = require('fs');
fs.readFile('readMe.txt', 'utf8', function (err, data) {
  fs.writeFile('writeMe.txt', data);
});

回答1:


Fs.writeFile() according to the documentation here takes ( file, data[, options]and callback ) params so your code will be like this :

 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);
   });
 });



回答2:


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(...)

See node fs docs for more info.




回答3:


Since node 10, it is mandatory to pass a callback on 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

You could add an empty callback like this fs.writeFile('writeMe.txt', data, () => {})




回答4:


you also use like this

var file2 = await fs.readFileSync("./Public/n2.jpeg")



回答5:


This error hit me in the face when I was doing the following;

var hello = myfunction( callme() );

rather than

var hello = myfunction( callme );



来源:https://stackoverflow.com/questions/51150956/how-to-fix-this-error-typeerror-err-invalid-callback-callback-must-be-a-funct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!