How to remove a file with Node.js?

Sometimes, we want to remove a file with Node.js.

In this article, we’ll look at how to remove a file with Node.js.

How to remove a file with Node.js?

To remove a file with Node.js, we can use the fs.unlink` method.

For instance, we write

fs.unlink('./server/my.csv', (err) => {
  if (err) {
    return console.log(err);
  }
  console.log('file deleted successfully');
});

to call fs.unlink with the path of the file to delete and a callback that runs when unlink is finished.

err is set when there’s an error.

We can also call unlinkSync to delete a file synchronously.

For instance, we write

const fs = require('fs');
const filePath = './server/my.csv';
fs.unlinkSync(filePath);

to call unlinkSync with the filePath of the file to delete.

Conclusion

To remove a file with Node.js, we can use the fs.unlink` method.