How to remove a directory asynchronously using Node.js?

April 13, 2021 - 2 min read

To remove a directory or a folder, we can use the rmdir() method from the fs (filesystem) module Node.js. This will asynchronously remove the directory.

// Remove directory asynchronously
fs.rmdir("./FilesDirectory", { recursive: true }, () => {
  console.log("Successfully deleted directory!");
});

For exampe let's consider a directory called FilesDirectory like this,

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

// path
const path = "./FilesDirectory";

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

  • pass the path as the first argument
  • optional options object with a property of recursive set to boolean true as the second argument. This is done so that any files or directories inside the directory are also deleted. If you don't want a directory with files not to be deleted, you can remove the options object completely.
  • and an error first callback function as the third argument

to the function like this,

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

// path
const path = "./FilesDirectory";

// remove directory by passing path
// as the first argument to the function
fs.rmdir(path, { recursive: true }, (error) => {
  // if any error
  if (error) {
    console.error(error);
    return;
  }

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

See this example live in repl.it.

Feel free to share if you found this useful 😃.