Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node how to remove a directory if exists?

Tags:

node.js

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

like image 446
francesca Avatar asked Dec 20 '22 01:12

francesca


2 Answers

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.

like image 85
Jarrod Avatar answered Jan 02 '23 19:01

Jarrod


Two Liner:

if (fs.existsSync(dir)) {
  fs.rmdirSync(dir, {recursive: true})
}
like image 43
nick Avatar answered Jan 02 '23 18:01

nick