为什么节点10强制在fs

为什么节点10强制在fs

本文介绍了为什么节点10强制在fs.writeFile()上传递回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

正在与节点4.5一起工作的代码:fs.writeFile(target, content);

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

经过一些调试后,我在node_internal/fs.js中找到了它:

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

当然,如果在这里不传递第三/第四参数,我的代码将失败.我想知道有什么办法可以减轻这个问题.否则,这种突破性变革背后的动机可能是什么.毕竟,fs.writeFile()是这样的基本操作,诸如此类的问题在升级时确实很痛苦.

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.

推荐答案

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

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

这里还有很多讨论: 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.

这篇关于为什么节点10强制在fs.writeFile()上传递回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 20:51