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

后端 未结 22 1787
清歌不尽
清歌不尽 2021-01-31 13:41

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

22条回答
  •  别跟我提以往
    2021-01-31 14:00

    Use child_process.execFile it is faster.

    NodeJS docs:

    child_process.execFile is similar to child_process.exec() except it* does not execute a subshell but rather the specified file directly.

    This works. Mimicking rm -rf DIR...

    var child = require('child_process');
    
    var rmdir = function(directories, callback) {
        if(typeof directories === 'string') {
            directories = [directories];
        }
        var args = directories;
        args.unshift('-rf');
        child.execFile('rm', args, {env:process.env}, function(err, stdout, stderr) {
                callback.apply(this, arguments);
        });
    };
    
    // USAGE
    rmdir('dir');
    rmdir('./dir');
    rmdir('dir/*');
    rmdir(['dir1', 'dir2']);
    

    Edit: I have to admit this is not cross-platform, will not work on Windows

提交回复
热议问题