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


当前回答

[编辑:使用node.js v15.5.0]

刚刚尝试使用这里发布的一些解决方案后,我遇到了以下弃用警告:

(node:13202) [DEP0147] DeprecationWarning:在未来的版本 node . js, fs。Rmdir (path, {recursive: true})将抛出 不存在或者是一个文件。使用fs。Rm (path, {recursive: true, force: true }),而不是

fs。Rm (path,{递归:true, force: true});与fs一起工作很好。rmSync(path,{递归:true, force: true});如果你想使用阻塞版本。

其他回答

截至节点v14(2020年10月),fs模块有fs。rm和rs.rmSync支持递归非空目录解链接:

https://nodejs.org/docs/latest-v14.x/api/fs.html#fs_fs_rm_path_options_callback

所以你现在可以这样做:

const fs = require('fs');
fs.rm('/path/to/delete', { recursive: true }, () => console.log('done'));

or:

const fs = require('fs');
fs.rmSync('/path/to/delete', { recursive: true });
console.log('done');

超速度和防故障

你可以使用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/');

只需使用rmdir模块!这很简单。

如果你更喜欢async/await,你可以使用fs/promises API。

const fs = require('fs/promises');

const removeDir = async (dirPath) => {
  await fs.rm(dirPath, {recursive: true});
}

如果您知道文件夹中单个文件的路径,并希望删除包含该文件的文件夹。

const fs = require('fs/promises');
const path = require('path');

const removeDir = async (filePath) => {
  const { dir } = path.parse(filePath);
  await fs.rm(dir, { recursive: true });
}

而递归是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);
            });
        });
    });
}