Is node.js rmdir recursive ? Will it work on non empty directories?

The documentation for fs.rmdir is very short and doesn't explain the behavior of rmdir when the directory is not empty.

Q: What happens if I try to use this API to delete a non empty directory ?


Solution 1:

Although using a third-party library for such a thing I could not come up with a more elegant solution. So I ended up using the npm-module rimraf.

Install it

npm install rimraf

Or install it and save to 'package.json' (other save options can be found in the npm-install docs)

npm install --save rimraf

Then you can do the following:

rmdir = require('rimraf');
rmdir('some/directory/with/files', function(error){});

Or in Coffeescript:

rmdir = require 'rimraf'
rmdir 'some/directory/with/files', (error)->

Solution 2:

I wrote about this problem exactly.

My previous solution below, while simple, is not preferred. The following function, is a Synchronous solution; while async might be preferred.

deleteFolderRecursive = function(path) {
    var files = [];
    if( fs.existsSync(path) ) {
        files = fs.readdirSync(path);
        files.forEach(function(file,index){
            var curPath = path + "/" + file;
            if(fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
};

[Edit] Added lstat instead of stat to prevent errors on symlinks

[Previous Solution]

My solution to this is quite easy to implement.

var exec = require('child_process').exec,child;
child = exec('rm -rf test',function(err,out) { 
  console.log(out); err && console.log(err); 
});

This is slimmed down for this page, but the basic idea is simple; execute 'rm -r' on the command line. If your app needs to run across different types of OS, put this in a function and have an if/else/switch to handle it.

You will want to handle all the responses; but the idea is simple enough.

Solution 3:

Short answer: node.js fs.rmdir() calls the POSIX rmdir(); this will remove an empty directory, or return an error. In the given case, the call will invoke the callback function and pass the error as an exception.

The problem here is that the node.js documentation refers to POSIX:

The Node.js API Docs File System API started out as

simple wrappers around standard POSIX functions.

This almost changes the question into a duplicate of: Is there a listing of the POSIX API / functions?

The description for fs.rmdir is terse, but sufficient.

Asynchronous rmdir(2).

The rmdir(2) here is an implicit reference to the documentation for the rmdir() system call. The number (2) here is an old unix man page convention to indicate Section 2 of the Manual pages, containing the kernel interfaces.

Solution 4:

Node.js v12.10.0 introduced recursive option into fs.rmdir. As fs.mkdir supports the same option since v10.12.0, both making and removing directory can be executed recursively.

$ node --experimental-repl-await

# without recursive option -> error
> await fs.promises.mkdir('foo/bar')
Thrown:
[Error: ENOENT: no such file or directory, mkdir 'foo/bar'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'mkdir',
  path: 'foo/bar'
}

# with recursive option -> success
> await fs.promises.mkdir('foo/bar', { recursive: true })
undefined

# without recursive option -> error
> await fs.promises.rmdir('foo')
Thrown:
[Error: ENOTEMPTY: directory not empty, rmdir 'foo'] {
  errno: -66,
  code: 'ENOTEMPTY',
  syscall: 'rmdir',
  path: 'foo'
}

# with recursive option -> success
> await fs.promises.rmdir('foo', { recursive: true })
undefined