How to delete a non-empty directory in Node.js

#nodejs

Last updated on May 11, 2022 by Suraj Sharma



In this tutorial, you’ll learn how you can delete a non-empty directory programmatically in node.js

Whenever I need to delete a directory, I use the rmSync function present in the fs module

The rmSync function takes two arguments, the directory path and an option object.


  const fs = require('fs');

  try {
    fs.rmSync('./folder-to-be-deleted');
    console.log(The directory is deleted.);
  } catch (err) {
    console.error(Error while deleting the directory.);
  }

If your directory contains inner directories then you have to set recursive to true to delete directories recursively otherwise the function will throw an error


  const fs = require('fs');

  try {
    // delete directory recursively
    fs.rmSync('./folder-to-be-deleted', { recursive: true });
    console.log(The directory is deleted.);
  } catch (err) {
    console.error(Error while deleting the directory.);
  }


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.