在我的节点应用程序中,我需要删除一个目录,其中有一些文件,但fs。Rmdir只适用于空目录。我该怎么做呢?


当前回答

从Node文档中可以看到。

要获得类似rm -rf Unix命令的行为,请使用带有选项{recursive: true, force: true}的fs.rm()。

例如(ESM)

import { rm } from 'node:fs/promises';

await rm('/path/to', { recursive: true, force: true });

其他回答

同步删除文件夹

    const fs = require('fs');
    const Path = require('path');

    const deleteFolderRecursive = function (directoryPath) {
    if (fs.existsSync(directoryPath)) {
        fs.readdirSync(directoryPath).forEach((file, index) => {
          const curPath = path.join(directoryPath, file);
          if (fs.lstatSync(curPath).isDirectory()) {
           // recurse
            deleteFolderRecursive(curPath);
          } else {
            // delete file
            fs.unlinkSync(curPath);
          }
        });
        fs.rmdirSync(directoryPath);
      }
    };

超速度和防故障

你可以使用lignator包(https://www.npmjs.com/package/lignator),它比任何异步代码(例如rimraf)都快,而且更防故障(特别是在Windows中,文件删除不是瞬时的,文件可能被其他进程锁定)。

4,36 GB的数据,28042个文件,4217个文件夹在Windows上在15秒内删除,而旧硬盘上的rimraf只有60秒。

const lignator = require('lignator');

lignator.remove('./build/');

而递归是fs.rmdir的一个实验性选项

function rm (path, cb) {
    fs.stat(path, function (err, stats) {
        if (err)
            return cb(err);

        if (stats.isFile())
            return fs.unlink(path, cb);

        fs.rmdir(path, function (err) {
            if (!err || err && err.code != 'ENOTEMPTY') 
                return cb(err);

            fs.readdir(path, function (err, files) {
                if (err)
                    return cb(err);

                let next = i => i == files.length ? 
                    rm(path, cb) : 
                    rm(path + '/' + files[i], err => err ? cb(err) : next(i + 1));

                next(0);
            });
        });
    });
}

同步文件夹删除文件或仅一个文件。 我不是一个很好的给予者,也不是一个贡献者,但我找不到一个很好的解决这个问题的方法,我必须找到我的方法……所以我希望你会喜欢它:) 适用于任何数量的嵌套目录和子目录。注意递归函数时'this'的作用域,您的实现可能不同。在我的例子中,这个函数保留在另一个函数的返回中这就是为什么我用这个来调用它。

    const fs = require('fs');

    deleteFileOrDir(path, pathTemp = false){
            if (fs.existsSync(path)) {
                if (fs.lstatSync(path).isDirectory()) {
                    var files = fs.readdirSync(path);
                    if (!files.length) return fs.rmdirSync(path);
                    for (var file in files) {
                        var currentPath = path + "/" + files[file];
                        if (!fs.existsSync(currentPath)) continue;
                        if (fs.lstatSync(currentPath).isFile()) {
                            fs.unlinkSync(currentPath);
                            continue;
                        }
                        if (fs.lstatSync(currentPath).isDirectory() && !fs.readdirSync(currentPath).length) {
                            fs.rmdirSync(currentPath);
                        } else {
                            this.deleteFileOrDir(currentPath, path);
                        }
                    }
                    this.deleteFileOrDir(path);
                } else {
                    fs.unlinkSync(path);
                }
            }
            if (pathTemp) this.deleteFileOrDir(pathTemp);
        }

在Node.js的最新版本(12.10.0或更高版本)中,rmdir样式函数fs.rmdir()、fs.rmdirSync()和fs.promises.rmdir()有一个新的实验性选项递归,允许删除非空目录,例如:

fs.rmdir(path, { recursive: true });

GitHub上的相关PR: https://github.com/nodejs/node/pull/29168