How to check if file was deleted?

To delete a file in Nodejs, we can use fs.unlink(path, callback).

The callback will be called after the operation completes and depending on the result, its first argument will be either Error object (telling us something went wrong), or null (deletion of file was successful).

const fs = require('fs');
const filePath = __dirname + '/file-to-delete.txt';

fs.unlink(filePath, err => {
  // ENOENT (No such file or directory)
  if (err && err.code === 'ENOENT') {
    return console.log(`File ${filePath} does not exist!`);

  console.log(`Deleted ${filePath}`);