Why node 10 has made it mandatory to pass callback on fs.writeFile()?

帅比萌擦擦* 提交于 2019-12-12 17:50:48

问题


Suddenly, I started getting this error on my application when the node engine was upgraded to 10.7.0

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function

Code which was working with node 4.5: fs.writeFile(target, content);

After a bit of debugging I found this in node_internal/fs.js:

function writeFile(path, data, options, callback) {
  callback = maybeCallback(callback || options);
  ...
}
function maybeCallback(cb) {
  if (typeof cb === 'function')
    return cb;
  throw new ERR_INVALID_CALLBACK();
}

Certainly, if do not pass a third/fourth argument here, my code will fail. I want to know is there any way to mitigate this problem. Or if not, what could be the motivation behind such a breaking change. After all, fs.writeFile() is such a basic operation, issues such as these are really a pain while upgrading.


回答1:


Node.js has documented the purpose for this change: https://github.com/nodejs/node/blob/master/doc/api/deprecations.md#dep0013-fs-asynchronous-function-without-callback

There is a lot more discussion here: https://github.com/nodejs/node/pull/12562#issuecomment-300734746

In fact it seems like some developers agree with you, however the decision has been made and the callback is now required.

There is no mitigation per se; you will just have to add a callback. Even an empty one will work okay:

fs.writeFile(target, content, () => {});

I understand this may require a lot of changes for currently working code, but in fact it might be a good opportunity for you to add error handling as well.



来源:https://stackoverflow.com/questions/52392192/why-node-10-has-made-it-mandatory-to-pass-callback-on-fs-writefile

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