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

后端 未结 22 1811
清歌不尽
清歌不尽 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 13:51

    Following on @geedew's answer.

    Here is an asynchronous implementation of rm -r (ie you can pass a path to a file or directory). I'm not an experienced nodejs developer and appreciate any suggestions or constructive criticism.

    var fs = require('fs');
    
    function ResultsCollector (numResultsExpected, runWhenDone) {
        this.numResultsExpected = numResultsExpected,
        this.runWhenDone = runWhenDone;
        this.numResults = 0;
        this.errors = [];
    
        this.report = function (err) {
            if (err) this.errors.push(err);
            this.numResults++;
            if (this.numResults == this.numResultsExpected) {
                if (this.errors.length > 0) return runWhenDone(this.errors);
                else return runWhenDone();
            }
        };
    }
    
    function rmRasync(path, cb) {
        fs.lstat(path, function(err, stats) {
            if (err && err.code == 'ENOENT') return cb(); // doesn't exist, nothing to do
            else if (err) {
                return cb(err);
            }
            if (stats.isDirectory()) {
                fs.readdir(path, function (err, files) {
                    if (err) return cb(err);
                    var resultsCollector = new ResultsCollector(files.length, function (err) {
                        if (err) return cb(err);
                        fs.rmdir(path, function (err) {
                            if (err) return cb(err);
                            return cb();
                        });
                    });
                    files.forEach(function (file) {
                        var filePath = path + '/' + file;
                        return rmRasync(filePath, function (err) {
                            return resultsCollector.report(err);
                        });
                    });
                });
            }
            else { // file.
                // delete file or link
                fs.unlink(path, function (err) {
                    if (err) return cb(err);
                    return cb();
                });
            }
        });
    };
    

    Invoke like so:

    rmRasync('/path/to/some/file/or/dir', function (err) {
        if (err) return console.error('Could not rm', err);
        // else success
    });
    

提交回复
热议问题