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

后端 未结 22 1654
清歌不尽
清歌不尽 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:58

    I realize this isn't exactly answering the question at hand, but I think this might be useful to someone searching here in the future (it would have been to me!): I made a little snippet that allows one to recursively delete only empty directories. If a directory (or any of its descendant directories) has content inside it, it is left alone:

    var fs = require("fs");
    var path = require("path");
    
    var rmdir = function(dir) {
        var empty = true, list = fs.readdirSync(dir);
        for(var i = list.length - 1; i >= 0; i--) {
            var filename = path.join(dir, list[i]);
            var stat = fs.statSync(filename);
    
            if(filename.indexOf('.') > -1) {
                //There are files in the directory - we can't empty it!
                empty = false;
                list.splice(i, 1);
            }
        }
    
        //Cycle through the list of sub-directories, cleaning each as we go
        for(var i = list.length - 1; i >= 0; i--) {
            filename = path.join(dir, list[i]);
            if (rmdir(filename)) {
                list.splice(i, 1);
            }
        }
    
        //Check if the directory was truly empty
        if (!list.length && empty) {
            console.log('delete!');
            fs.rmdirSync(dir);
            return true;
        }
        return false;
    };
    

    https://gist.github.com/azaslavsky/661020d437fa199e95ab

提交回复
热议问题