I'm trying to remove node_modules directory if it exists and is not empty

var fs = require('fs'),
    path = require('path'),
    child_process = require('child_process'),
    cmd;

module.exports = function(){
    var modulesPath = '../modules';

    fs.readdirSync(modulesPath)
        .forEach(function(dir) {
            var location = path.join(dir, 'node_modules');
            if (fs.existsSync(location)){
                fs.rmdir(location);
            }
        });
};

However, fs.rmdir command unfortunately removes directory only if there are no files there.

NodeJS doesn’t have an easy way to force the removal

Update v16 - Async & Recursive Method

You can now use fs.rm() or fs.promises.rm() like this:

fs.rm("/directory-to-delete", { recursive: true, force: true })

Options:

  • recursive <boolean> If true, perform a recursive directory removal.
  • force <boolean> If true, exceptions will be ignored if path does not exist.

Further Reading