How to remove a file asynchronously using Node.js?

Published December 20, 2020

To remove a file, we can use the unlink() function from the fs (filesystem) module Node.js. This will asynchronously remove the file.

// Remove file asynchronously
fs.unlink("file.txt", () => {
  console.log("Successfully deleted file!");
});

For exampe let's consider a file called file.txt like this,

// require fs module
const fs = require("fs");

// path
const path = "file.txt";

Now let's use the fs.unlink() function and

  • pass the path as the first argument
  • and an error first callback function as the second argument

to the function like this,

// require fs module
const fs = require("fs");

// path
const path = "file.txt";

// remove file by passing path
// as the first argument to the function
fs.unlink(path, (error) => {
  // if any error
  if (error) {
    console.error(error);
    return;
  }

  console.log("Successfully deleted file!");
});

See this example live in repl.it.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter