在我的节点应用程序中,我需要删除一个目录,其中有一些文件,但fs。Rmdir只适用于空目录。我该怎么做呢?
当前回答
❄️您可以使用graph-fs
directory.delete()
其他回答
方法删除非空目录
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中使用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);
const fs = require("fs")
const path = require("path")
let _dirloc = '<path_do_the_directory>'
if (fs.existsSync(_dirloc)) {
fs.readdir(path, (err, files) => {
if (!err) {
for (let file of files) {
// Delete each file
fs.unlinkSync(path.join(_dirloc, file))
}
}
})
// After the 'done' of each file delete,
// Delete the directory itself.
if (fs.unlinkSync(_dirloc)) {
console.log('Directory has been deleted!')
}
}
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!`);
});
});
我通常不复活旧线程,但这里有很多关于搅动和没有rimraf的答案,这些对我来说似乎都太复杂了。
首先,在现代Node (>= v8.0.0)中,你可以只使用节点核心模块来简化过程,完全异步,并在5行函数中并行化文件的解链接,并且仍然保持可读性:
const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const readdir = promisify(fs.readdir);
const rmdir = promisify(fs.rmdir);
const unlink = promisify(fs.unlink);
exports.rmdirs = async function rmdirs(dir) {
let entries = await readdir(dir, { withFileTypes: true });
await Promise.all(entries.map(entry => {
let fullPath = path.join(dir, entry.name);
return entry.isDirectory() ? rmdirs(fullPath) : unlink(fullPath);
}));
await rmdir(dir);
};
另一方面,路径遍历攻击的保护不适合此函数,因为
It is out of scope based on the Single Responsibility Principle. Should be handled by the caller not this function. This is akin to the command-line rm -rf in that it takes an argument and will allow the user to rm -rf / if asked to. It would be the responsibility of a script to guard not the rm program itself. This function would be unable to determine such an attack since it does not have a frame of reference. Again that is the responsibility of the caller who would have the context of intent which would provide it a reference to compare the path traversal. Sym-links are not a concern as .isDirectory() is false for sym-links and are unlinked not recursed into.
最后但并非最不重要的是,有一种罕见的竞争条件,即在运行递归时,如果在正确的时间在脚本之外取消链接或删除其中一个条目,则递归可能会出错。由于这种情况在大多数环境中并不典型,因此可能会被忽略。然而,如果需要(对于一些边缘情况),这个问题可以通过下面这个稍微复杂一点的例子来缓解:
exports.rmdirs = async function rmdirs(dir) {
let entries = await readdir(dir, { withFileTypes: true });
let results = await Promise.all(entries.map(entry => {
let fullPath = path.join(dir, entry.name);
let task = entry.isDirectory() ? rmdirs(fullPath) : unlink(fullPath);
return task.catch(error => ({ error }));
}));
results.forEach(result => {
// Ignore missing files/directories; bail on other errors
if (result && result.error.code !== 'ENOENT') throw result.error;
});
await rmdir(dir);
};
编辑:使isDirectory()成为一个函数。最后删除实际目录。修复丢失的递归。
推荐文章
- 如何确定在android文件的MIME类型?
- Node.js上的html解析器
- 错误:无法找到模块“webpack”
- 在node.js中使用async / await文件系统
- NodeJS -用NPM安装错误
- 如何为本地安装npm包设置自定义位置?
- 回调函数来处理管道的完成
- Express函数中的“res”和“req”参数是什么?
- node.js TypeError:路径必须是绝对路径或指定根路径到res.sendFile[解析JSON失败]
- Passport.js -错误:序列化用户到会话失败
- Node.js vs .Net性能
- 从电子应用程序中删除菜单栏
- 如何用node.js实现一个安全的REST API
- 如何处理Node.js中的循环依赖
- 在猫鼬,我如何排序的日期?(node . js)