Node.js – Remove directory which is not empty


In my Node application I need to remove a directory which has some files, but fs.rmdir only works on empty directories. How can I do this?

Best Solution

As of 2019...

As of Node.js 12.10.0, fs.rmdirSync supports a recursive options, so you can finally do:

fs.rmdirSync(dir, { recursive: true });

Where the recursive option deletes the entire directory recursively.

Update: The recursive option in fs.rmdir / fs.rmdirSync has been deprecated however, so use fs.rm / fs.rmSync instead:

fs.rmSync(dir, { recursive: true, force: true });

The force: true option ignores exceptions if dir does not exist. More info see the fs.rmSync docs