javascript 删除(取消链接)与正则表达式匹配的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14917757/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:55:24  来源:igfitidea点击:

Delete (unlink) files matching a regex

javascriptnode.jsfile-iofilesystems

提问by Joseph Silber

I want to delete several files from a directory, matching a regex. Something like this:

我想从一个目录中删除几个文件,匹配一个正则表达式。像这样的东西:

// WARNING: not real code
require('fs').unlink(/script\.\d+\.js$/);


Since unlinkdoesn't support regexes, I'm using this instead:

由于unlink不支持正则表达式,我用它来代替:

var fs = require('fs');

fs.readdir('.', (error, files) => {
    if (error) throw error;

    files.filter(name => /script\.\d+\.js$/.test(name)).forEach(fs.unlink);
});

which works, but IMO is a little more complex than it should be.

这是有效的,但 IMO 比它应该的要复杂一些。



Is there a better built-in way to delete files that match a regex (or even just use wildcards)?

是否有更好的内置方法来删除与正则表达式匹配的文件(甚至只使用通配符)?

采纳答案by user568109

You can look into glob https://npmjs.org/package/glob

您可以查看 glob https://npmjs.org/package/glob

require("glob").glob("*.txt", function (er, files) { ... });
//or
files = require("glob").globSync("*.txt");

glob internally uses minimatch. It works by converting glob expressions into JavaScript RegExp objects. https://github.com/isaacs/minimatch

glob 内部使用 minimatch。它的工作原理是将 glob 表达式转换为 JavaScript RegExp 对象。https://github.com/isaacs/minimatch

You can do whatever you want with the matched files in the callback (or in case of globSync the returned object).

您可以对回调中的匹配文件执行任何您想要的操作(或者在 globSync 的情况下返回的对象)。

回答by david.pfx

No there is no globbing in the Node libraries. If you don't want to pull in something from NPM then not to worry, it just takes a line of code. But in my testing the code provided in other answers mostly won't work. So here is my code fragment, tested, working, pure native Node and JS.

不,Node 库中没有通配符。如果你不想从 NPM 中提取一些东西,那么不用担心,它只需要一行代码。但是在我的测试中,其他答案中提供的代码大多不起作用。所以这是我的代码片段,经过测试,可以工作,纯原生 Node 和 JS。

let fs = require('fs')
const path = './somedirectory/'
let regex = /[.]txt$/
fs.readdirSync(path)
    .filter(f => regex.test(f))
    .map(f => fs.unlinkSync(path + f))

回答by Sumit Jindal

I have a very simple solution to do this. Read the directory in node.js using fs.readdir API. This will give an array of all the files in the directory. Once you have that array, iterate over it using for loop, apply regex. The below code will delete all files starting with "en" and extension ".js"

我有一个非常简单的解决方案来做到这一点。使用 fs.readdir API 读取 node.js 中的目录。这将给出目录中所有文件的数组。拥有该数组后,使用 for 循环对其进行迭代,应用正则表达式。下面的代码将删除所有以“en”和扩展名“.js”开头的文件

fs.readdir('.', (err, files)=>{
   for (var i = 0, len = files.length; i < len; i++) {
      var match = files[i].match(/en.*.js/);
      if(match !== null)
          fs.unlink(match[0]);
   }
});

回答by Will Nelson

The answer could depend on your environment. It looks like you are running on node.js. A quick perusal of the node.js documentation suggests there is no "built in" way to do this, i.e., there isn't a single function call that will do this for you. The next best thing might involve a small number of function calls. As I wrote in my comment, I don't think there's any easy way to make your suggested answer much briefer just relying on the standard node.js function calls. That is, if I were in your shoes, I would go with the solution you already suggested (though slightly cleaned up).

答案可能取决于您的环境。看起来您正在 node.js 上运行。快速阅读 node.js 文档表明没有“内置”方法可以做到这一点,即,没有一个函数调用可以为您做到这一点。下一个最好的事情可能涉及少量的函数调用。正如我在评论中所写的那样,我认为没有任何简单的方法可以仅依靠标准的 node.js 函数调用来使您建议的答案更简洁。也就是说,如果我站在你的立场上,我会采用你已经建议的解决方案(尽管稍微清理了一下)。

One alternative is to go to the shell, e.g.,

一种选择是转到外壳,例如,

var exec = require('child_process').exec;
exec('ls | grep "script[[:digit:]]\\+.js" | xargs rm');

Personally, I would strongly prefer your offered solution over this gobbledygook, but maybe you're shooting for something different.

就个人而言,我更喜欢你提供的解决方案而不是这个 gobbledygook,但也许你正在寻找不同的东西。