【问题标题】:node how to remove a directory if exists?如果存在,节点如何删除目录?
【发布时间】:2015-11-02 06:27:32
【问题描述】:

我正在尝试删除 node_modules 目录(如果它存在且不为空)

var fs = require('fs'),
    path = require('path'),
    child_process = require('child_process'),
    cmd;

module.exports = function(){
    var modulesPath = '../modules';

    fs.readdirSync(modulesPath)
        .forEach(function(dir) {
            var location = path.join(dir, 'node_modules');
            if (fs.existsSync(location)){
                fs.rmdir(location);
            }
        });
};

fs.rmdir 命令不幸的是,只有在没有文件的情况下才会删除目录。 NodeJS 没有简单的方法来强制删除

【问题讨论】:

标签: node.js


【解决方案1】:

@since 14.4.0

const fs = require('fs')

// note `fm.rm` and `fm.rmSync` can delete files and directories
// retry options not required - might be needed if an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or EPERM error is encountered
// the `force` option When true, exceptions will be ignored if path does not exist.
// the `recursive` If true, perform a recursive directory removal. In recursive mode, operations are retried on failure.

// async version - prefered - you may need to await the file deletion - works like `rm -rf`
fs.promises.rm(`<FILE|DIR_PATH>`, { maxRetries: 5, retryDelay: 2000, recursive: true, force: true })

// sync version - works like `rm -rf`
fs.rmSync(`<FILE|DIR_PATH>`, { maxRetries: 5, retryDelay: 2000, recursive: true, force: true })

参考:

【讨论】:

    【解决方案2】:

    两个班轮:

    if (fs.existsSync(dir)) {
      fs.rmdirSync(dir, {recursive: true})
    }
    

    【讨论】:

    • 您使用的两个函数都是同步的(因此是同步的)。异步变体可以从内置的“fs/promises”中导入,尽管存在已被贬值。 existsSync 处于活动状态,但又不是一个承诺。希望这会有所帮助!
    • 一个班轮:fs.rmSync('./dir', {force: true, recursive: true});Source
    【解决方案3】:

    有几点:

    你的 next(err) 函数来自哪里?

    还请记住,您正在调用的函数的 node.js 文档中的 rmdir 是这样的: https://nodejs.org/api/fs.html#fs_fs_rmdir_path_callback

    Asynchronous rmdir(2)
    

    这个的posix定义是:

    deletes a directory, which must be empty.
    

    确保您的目录是空的,在这种情况下似乎不是。

    这里有一个关于非空目录的要点:

    https://gist.github.com/tkihira/2367067

    var fs = require("fs");
    var path = require("path");
    
    var rmdir = function(dir) {
        var list = fs.readdirSync(dir);
        for(var i = 0; i < list.length; i++) {
            var filename = path.join(dir, list[i]);
            var stat = fs.statSync(filename);
    
            if(filename == "." || filename == "..") {
                // pass these files
            } else if(stat.isDirectory()) {
                // rmdir recursively
                rmdir(filename);
            } else {
                // rm fiilename
                fs.unlinkSync(filename);
            }
        }
        fs.rmdirSync(dir);
    };
    

    这里还有一个节点模块:

    https://github.com/dreamerslab/node.rmdir

    这些可能会让你走上正轨。

    【讨论】:

    【解决方案4】:
    var fs = require('fs');
    var path = require('path');
    var child_process = require('child_process');
    var cmd;
    
    module.exports = function(){
        var modulesPath = 'modules';
    
        fs.readdirSync(modulesPath)
            .forEach(function(dir) {
                var location = path.join(dir, 'node_modules');
                if (fs.existsSync(location)){
                    fs.rmdir(location, function (err) {
                        return next(err);
                    })
                }
            });
    };
    

    确保检查当前路径中的模块文件夹。

    【讨论】:

    • 在这种情况下next 是什么?
    • 我知道这个答案有点老了,但我提交了一个编辑请求,因为我认为这段代码应该是一个中间件(这就是next 关键字的原因)。接下来可能应该来自(req, res, next)(参数)。如果答案有一些描述,那就太好了。
    猜你喜欢
    • 2011-03-25
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多