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


当前回答

大多数在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);

其他回答

有一个模块叫做rimraf (https://npmjs.org/package/rimraf)。它提供了与rm -Rf相同的功能

异步用法:

var rimraf = require("rimraf");
rimraf("/some/directory", function () { console.log("done"); });

同步用法:

rimraf.sync("/some/directory");

[编辑:使用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});如果你想使用阻塞版本。

另一种替代方法是使用fs-promise模块,该模块提供fs-extra模块的承诺版本

你可以这样写:

const { remove, mkdirp, writeFile, readFile } = require('fs-promise')
const { join, dirname } = require('path')

async function createAndRemove() {
  const content = 'Hello World!'
  const root = join(__dirname, 'foo')
  const file = join(root, 'bar', 'baz', 'hello.txt')

  await mkdirp(dirname(file))
  await writeFile(file, content)
  console.log(await readFile(file, 'utf-8'))
  await remove(join(__dirname, 'foo'))
}

createAndRemove().catch(console.error)

注意:async/await需要最新的nodejs版本(7.6+)

事实上的包是rimraf,但这里是我的小异步版本:

const fs = require('fs')
const path = require('path')
const Q = require('q')

function rmdir (dir) {
  return Q.nfcall(fs.access, dir, fs.constants.W_OK)
    .then(() => {
      return Q.nfcall(fs.readdir, dir)
        .then(files => files.reduce((pre, f) => pre.then(() => {
          var sub = path.join(dir, f)
          return Q.nfcall(fs.lstat, sub).then(stat => {
            if (stat.isDirectory()) return rmdir(sub)
            return Q.nfcall(fs.unlink, sub)
          })
        }), Q()))
    })
    .then(() => Q.nfcall(fs.rmdir, dir))
}

大多数在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);