为什么节点 10 强制要求在 fs.writeFile() 上传递回调?

ImG*_*oot 4 fs node.js npm

突然,当节点引擎升级到 10.7.0 时,我的应用程序开始出现此错误

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
Run Code Online (Sandbox Code Playgroud)

与节点 4.5 一起使用的代码: fs.writeFile(target, content);

经过一番调试后,我在 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();
}
Run Code Online (Sandbox Code Playgroud)

当然,如果不在这里传递第三/第四个参数,我的代码将失败。我想知道有什么办法可以缓解这个问题。或者,如果没有,这种突破性变化背后的动机可能是什么。毕竟fs.writeFile()就是这么一个基本的操作,升级的时候遇到这样的问题真的很头疼。

Exp*_*lls 5

Node.js 已记录此更改的目的:https : //github.com/nodejs/node/blob/master/doc/api/deprecations.md#dep0013-fs-asynchronous-function-without-callback

这里有更多讨论:https : //github.com/nodejs/node/pull/12562#issuecomment-300734746

事实上,似乎有些开发人员同意你的看法,但决定已经做出,现在需要回调。

本身没有缓解措施;你只需要添加一个回调。即使是空的也可以正常工作:

fs.writeFile(target, content, () => {});
Run Code Online (Sandbox Code Playgroud)

我知道这可能需要对当前工作的代码进行大量更改,但实际上这也可能是您添加错误处理的好机会。