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?
There is a module for this called rimraf it provides the same functionality of rm -Rf
I wrote this function called remove folder. It will recursively remove all the files and folders in a location. The only package it requires is async.
var async = require('async');
function removeFolder(location, next) {
fs.readdir(location, function (err, files) {
async.each(files, function (file, cb) {
file = location + '/' + file
fs.stat(file, function (err, stat) {
if (err) {
return cb(err);
}
if (stat.isDirectory()) {
removeFolder(file, cb);
} else {
fs.unlink(file, function (err) {
if (err) {
return cb(err);
}
return cb();
})
}
})
}, function (err) {
if (err) return next(err)
fs.rmdir(location, function (err) {
return next(err)
})
})
})
}
Another workaround way is to run a shell command from Node.
var execSync = require('exec-sync');
execSync("rm -r " + yourPathHere);
Of course, you should npm install exec-sync first.