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

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

    This function will recursively delete a directory or file that you specify, synchronously:

    var path = require('path');
    
    function deleteRecursiveSync(itemPath) {
        if (fs.statSync(itemPath).isDirectory()) {
            _.each(fs.readdirSync(itemPath), function(childItemName) {
                deleteRecursiveSync(path.join(itemPath, childItemName));
            });
            fs.rmdirSync(itemPath);
        } else {
            fs.unlinkSync(itemPath);
        }
    }
    

    I have not tested this function's behavior if:

    • the item does not exist, or
    • the item cannot be deleted (such as due to a permissions issue).

提交回复
热议问题