Node how to delete a directory if it exists?

I am trying to remove the 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); } }); }; 

The fs.rmdir command, unfortunately, only removes a directory if there are no files there. NodeJS has no easy way to force removal.

+4
source share
2 answers

A few things:

where does your next function (err) come from?

Also remember that rmdir in the node.js documentation for the called function: https://nodejs.org/api/fs.html#fs_fs_rmdir_path_callback

 Asynchronous rmdir(2) 

Definition of posix:

 deletes a directory, which must be empty. 

Make sure your directory is empty , which in this case does not seem to be there.

Here there is the essence of transactions 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 here is node:

https://github.com/dreamerslab/node.rmdir

This may lead you to the right path.

+6
source
 var fs = require('fs'); var path = require('path'); var child_process = require('child_process'); var 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, function (err) { return next(err); }) } }); }; 

be sure to check the modules folder in the current path.

+1
source

All Articles