在我的节点应用程序中,我需要删除一个目录,其中有一些文件,但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});如果你想使用阻塞版本。

其他回答

我写了这个函数叫remove folder。它将递归地删除一个位置中的所有文件和文件夹。它唯一需要的包是异步的。

var async = require('async');

function removeFolder(location, next) {
    fs.readdir(location, function (err, files) {
        async.each(files, function (file, cb) {
            file = location + '/' + file
            fs.stat(file, function (err, stat) {
                if (err) {
                    return cb(err);
                }
                if (stat.isDirectory()) {
                    removeFolder(file, cb);
                } else {
                    fs.unlink(file, function (err) {
                        if (err) {
                            return cb(err);
                        }
                        return cb();
                    })
                }
            })
        }, function (err) {
            if (err) return next(err)
            fs.rmdir(location, function (err) {
                return next(err)
            })
        })
    })
}

截至节点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');
return new Promise((resolve, reject) => {
  const fs = require("fs");
  // directory path
  const dir = "your/dir";

  // delete directory recursively <------
  fs.rmdir(dir, { recursive: true }, (err) => {
    if (err) {
      reject(err);
    }
    resolve(`${dir} is deleted!`);
  });
});

同步删除文件夹

    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);
      }
    };

大多数在Node.js中使用fs的人都希望函数能够接近“Unix方式”来处理文件。我使用fs-extra来带来所有很酷的东西:

fs-extra包含了普通Node.js中不包含的方法 fs包。如mkdir -p、cp -r、rm -rf等。

更好的是,fs-extra是本地fs的替代品。fs中的所有方法都是未修改的,并附加到它。 这意味着你可以用fs-extra替换fs:

// this can be replaced
const fs = require('fs')

// by this
const fs = require('fs-extra')

然后你可以这样删除一个文件夹:

fs.removeSync('/tmp/myFolder'); 
//or
fs.remove('/tmp/myFolder', callback);