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

后端 未结 22 1362
清歌不尽
清歌不尽 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 13:42

    tried to make it fail safe as sync removal will cause error if file or dir are in use at that time.

        var path = require('path');
    var fs = require('fs')
    
    var dumpDirs = function (dir, name, cb) {
    fs.readdir(dir, function (err, files) {
        var dirs = [],
        filePath, i = 0, l = files.length;
        for (var i = 0; i < l; i++) {
            filePath = path.join(dir, files[i]);
            var stats = fs.lstatSync(filePath);
            if (stats.isDirectory()) {
                if (files[i].indexOf(name) != -1) {
                    dirs.push({
                        startOn: new Date(stats.ctime),
                        instance: files[i],
                        name: name
                    })
                }
            }
        }
        cb(dirs);
    });
    }
    
    var removeDir = function (dir, callback) {
    fs.readdir(dir, function (err, files) {
        c = files.length;
    
        (function remfile(i, cb) {
            if (i >= c)
                return cb();
            var p = path.join(dir, files[i])
            fs.unlink(p, function (err) {
                if (err) console.log(err);
                remfile(i + 1, cb)
            });
    
        })(0, function () {
            fs.rmdir(dir, function (err) {
                callback()
            });
        });
    
        //for (var i = 0; i < c; i++) {
        //    fs.unlinkSync(path.join(dir, files[i]));
        //};
    
    
    });
    }
    dumpDirs(maindir, function (dirs) {
    
    if (dirs && dirs.length > 0) {
        (function rem(i, cb) {
            if (i >= dirs.length) {
                return cb();
            }
            var folder = path.join(dump, dirs[i].instance);
            removeDir(folder, function () {
                rem(i + 1, cb);
            });
        })(0, function () {
            callback();
        })
    }
    else {
        callback();
    }
    });
    

提交回复
热议问题