在我的节点应用程序中,我需要删除一个目录,其中有一些文件,但fs。Rmdir只适用于空目录。我该怎么做呢?
当前回答
这是一种使用promisify和两个帮助函数(to和toAll)来解决承诺的方法。
它以异步方式执行所有操作。
const fs = require('fs');
const { promisify } = require('util');
const to = require('./to');
const toAll = require('./toAll');
const readDirAsync = promisify(fs.readdir);
const rmDirAsync = promisify(fs.rmdir);
const unlinkAsync = promisify(fs.unlink);
/**
* @author Aécio Levy
* @function removeDirWithFiles
* @usage: remove dir with files
* @param {String} path
*/
const removeDirWithFiles = async path => {
try {
const file = readDirAsync(path);
const [error, files] = await to(file);
if (error) {
throw new Error(error)
}
const arrayUnlink = files.map((fileName) => {
return unlinkAsync(`${path}/${fileName}`);
});
const [errorUnlink, filesUnlink] = await toAll(arrayUnlink);
if (errorUnlink) {
throw new Error(errorUnlink);
}
const deleteDir = rmDirAsync(path);
const [errorDelete, result] = await to(deleteDir);
if (errorDelete) {
throw new Error(errorDelete);
}
} catch (err) {
console.log(err)
}
};
其他回答
只需使用rmdir模块!这很简单。
@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);
}
};
从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 });
超速度和防故障
你可以使用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/');
[编辑:使用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});如果你想使用阻塞版本。
推荐文章
- ReferenceError: description没有定义NodeJs
- 将一个二进制的NodeJS Buffer转换为JavaScript的ArrayBuffer
- AngularJS只适用于单页应用程序吗?
- 如何在vue-cli项目中更改端口号
- 同步和异步编程(在node.js中)的区别是什么?
- 如何编辑通过npm安装的节点模块?
- “node_modules”文件夹应该包含在git存储库中吗
- 使用package.json在全局和本地安装依赖项
- this.libOptions.parse不是一个函数
- 对嵌套文件夹运行npm install的最好方法是什么?
- 节点Multer异常字段
- 很好的初学者教程socket.io?
- CALL_AND_RETRY_LAST分配失败-进程内存不足
- 在Ubuntu上安装Node.js
- 使用express.js代理