在 node.js 上使用 rimraf 删除所有子目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28770533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove all sub directories with rimraf on node.js
提问by Nat Naydenova
I have a directory structure where certain folder Data has sub directories. At some point I want those removed all at once and I've installed the otherwise awesome rimrafpackage for node.js
我有一个目录结构,其中某些文件夹 Data 具有子目录。在某些时候,我希望将它们一次性全部删除,并且我已经为 node.js安装了其他很棒的rimraf包
My code so far:
到目前为止我的代码:
var dataPath === Path.normalize(__dirname + '/backend/data/');
rimraf(dataPath, function(error) {
console.log('Error: ', error);
});
I've tried with both /backend/data/and /backend/data/*, but none seems to do the trick - the first deletes the entire datafolder and the second fires an error 'Can't delete null'
我已经尝试过/backend/data/和/backend/data/*,但似乎都没有成功 - 第一个删除整个数据文件夹,第二个触发错误“无法删除空值”
I guess I could scan the main directory, find all sub folders and delete them one by one, but if this can be done with rimrafor a similar package, I'd rather go with it.
我想我可以扫描主目录,找到所有子文件夹并一个一个删除它们,但是如果可以使用rimraf或类似的包来完成,我宁愿使用它。
回答by Trott
The easiest solution is to just re-create the datadirectory after rimraffinishes deleting it. Depending on your use case, that can introduce a race condition, but I doubt rimrafitself is race-safe in any situations where that isn't.
最简单的解决方案是data在rimraf完成删除后重新创建目录。根据您的用例,这可能会引入竞争条件,但我怀疑rimraf它在任何情况下都不是竞争安全的。
Another option is to read the contents of the directory and rimrafeach of those, but that is more work and doesn't avoid any race conditions that would affect the first option.
另一种选择是读取目录的内容和rimraf每个目录的内容,但这需要更多的工作,并且不会避免任何会影响第一个选项的竞争条件。
回答by bchr02
The current version of rimraf supports globs, so one could just add an asterisk to the end of the folder, like so:
当前版本的 rimraf 支持 globs,因此可以在文件夹末尾添加一个星号,如下所示:
rimraf( path.join(__dirname, "./uploads/*"), (err) => { ... });
rimraf( path.join(__dirname, "./uploads/*"), (err) => { ... });

