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

Viewed 1773

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 Answers

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.

Related