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
A couple of things:
where does your next(err) function come from?
Also remember that rmdir in node.js documentation for the function you are calling is this: https://nodejs.org/api/fs.html#fs_fs_rmdir_path_callback
Asynchronous rmdir(2)
The posix definition of this is:
deletes a directory, which must be empty.
Make sure your directory is empty, which in this case it seems it would not be.
There is a gist here the deals with non-empty directories:
https://gist.github.com/tkihira/2367067
var fs = require("fs");
var path = require("path");
var rmdir = function(dir) {
var list = fs.readdirSync(dir);
for(var i = 0; i < list.length; i++) {
var filename = path.join(dir, list[i]);
var stat = fs.statSync(filename);
if(filename == "." || filename == "..") {
// pass these files
} else if(stat.isDirectory()) {
// rmdir recursively
rmdir(filename);
} else {
// rm fiilename
fs.unlinkSync(filename);
}
}
fs.rmdirSync(dir);
};
And a node module here:
https://github.com/dreamerslab/node.rmdir
These might get you on the right track.
Two Liner:
if (fs.existsSync(dir)) {
fs.rmdirSync(dir, {recursive: true})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With