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


当前回答

我修改后的答案来自@oconnecp (https://stackoverflow.com/a/25069828/3027390)

使用路径。加入可以获得更好的跨平台体验。 所以,不要忘记要求它。

var path = require('path');

也将函数重命名为rimraf;)

/**
 * Remove directory recursively
 * @param {string} dir_path
 * @see https://stackoverflow.com/a/42505874/3027390
 */
function rimraf(dir_path) {
    if (fs.existsSync(dir_path)) {
        fs.readdirSync(dir_path).forEach(function(entry) {
            var entry_path = path.join(dir_path, entry);
            if (fs.lstatSync(entry_path).isDirectory()) {
                rimraf(entry_path);
            } else {
                fs.unlinkSync(entry_path);
            }
        });
        fs.rmdirSync(dir_path);
    }
}

其他回答

根据fs文档,fsPromises目前在实验的基础上提供了递归选项,至少在我自己的Windows上,它删除了目录和其中的任何文件。

fsPromises.rmdir(path, {
  recursive: true
})

递归:true是否删除Linux和MacOS上的文件?

@SharpCoder的答案使用fs.promises的异步版本:

const fs = require('fs');
const afs = fs.promises;

const deleteFolderRecursive = async path =>  {
    if (fs.existsSync(path)) {
        for (let entry of await afs.readdir(path)) {
            const curPath = path + "/" + entry;
            if ((await afs.lstat(curPath)).isDirectory())
                await deleteFolderRecursive(curPath);
            else await afs.unlink(curPath);
        }
        await afs.rmdir(path);
    }
};

如果你更喜欢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 });
}

方法删除非空目录

rmdir(path,{recursive:true,force:true}
rm(path,{recursive:true,force:true}

将工作

代码片段:

const fsp = require("fs/promises");

deleteDirRecursively("./b");
removeRecursively("./BCD/b+");

async function deleteDirRecursively(dirPath) {
  try {
    // fsPromises.rmdir() on a file (not a directory) results in the promise being rejected
    // with an ENOENT error on Windows and an ENOTDIR error on POSIX.
    // To get a behavior similar to the rm -rf Unix command,
    // use fsPromises.rm() with options { recursive: true, force: true }.
    //will not thorw error if dir is empty
    //will thow error if dir is not present
    await fsp.rmdir(dirPath, { recursive: true, force: true });
    console.log(dirPath, "deleted successfully");
  } catch (err) {
    console.log(err);
  }

async function removeRecursively(path) {
  try {
    //has ability to remove both file and dir
    //can delete dir recursively and forcefully
    //will delete an empty dir.
    //will remove all the contents of a dir.
    // the only difference between rmdir and rm is that rmdir can only delete dir's
    await fsp.rm(path, { recursive: true, force: true });
    console.log(path, "deleted successfully");
  } catch (err) {
    console.log(err);
  }
}

从Node.js 14.14.0开始,推荐使用fs.rmSync:

fs.rmSync(dir, { recursive: true, force: true });