fsPromises.writeFile callback not being called in Node v12.13.0

Viewed 1166

For whatever reason the callback for fs.promises is not being called, yet the documentation makes no mention of it only being called if there's an error, which is what I'm assuming would happen...

fsp.writeFile('test.txt', 'callback doesnt work', 'utf8', (error) => {
  console.log('callback is never called')
  if (error) console.error(error)
})

This is happening (or not happening lol) on version 12.13.0 of Node.

Does anybody know what the deal with this is?

1 Answers

The fs.promises version of async calls return promises. They don't accept callbacks. Use the regular fs version if you want to use a callback.

You can see right here in the doc that there is no option to pass a callback for the fsPromises versions of the API.

You should be doing it like this:

const fsp = require('fs').promises;

fsp.writeFile('test.txt', 'promise works', 'utf8').then(() => {
    console.log("write successful");
}).catch(err => {
    console.error(err);
});

Or, inside an async function, you could use try/catch and await instead of .then() and .catch().

Related