How to remove a directory which is not empty with Node.js?

Sometimes, we want to remove a directory which is not empty with Node.js.

In this article, we’ll look at how to remove a directory which is not empty with Node.js.

How to remove a directory which is not empty with Node.js?

To remove a directory which is not empty with Node.js, we can use the rm or rmSync method.

For instance, we write

const fs = require('fs');

fs.rm('/path/to/delete', {
  recursive: true
}, () => console.log('done'));

to call fs.rm with the path to delete as the first argument.

We set recursive to true in the object in the 2nd argument to let us delete an non-empty directory.

The 3rd argument is a callback that runs when rm is done.

rm will delete the directory asynchronously.

We call rmSync to delete a non-empty directory synchronously.

For instance, we write

const fs = require('fs');
fs.rmSync('/path/to/delete', {
  recursive: true
});
console.log('done');

to call rmSync with the path of the directory to delete and the same object as the arguments.

Conclusion

To remove a directory which is not empty with Node.js, we can use the rm or rmSync method.