Using node-glob, is it possible to specify a pattern that will return only the first X matching files, rather than all matches?
使用node-glob,是否可以指定仅返回前X个匹配文件的模式,而不是所有匹配?
For example, if I wanted all JavaScript files, my pattern would be **/*.js
. But what if I only wanted the first 5 JavaScript files?
例如,如果我想要所有JavaScript文件,我的模式将是** / * .js。但是,如果我只想要前5个JavaScript文件呢?
I realize that there are other options, such as I could take the resulting fileset array and slice it. The underlying case here makes that difficult, so I am trying to accomplish this directly from the glob pattern.
我意识到还有其他选项,例如我可以获取生成的文件集数组并对其进行切片。这里的基础案例很难,所以我试图直接从glob模式完成这个。
1 个解决方案
#1
3
You can create your own Glob object like this:
您可以像这样创建自己的Glob对象:
var i = 0;
var Glob = require("glob").Glob;
var mg = new Glob(pattern, options, cb);
mg.on("match", function(matched) {
console.log(matched);
i++;
if(i == 5) mg.abort();
});
It is an event emitter so you can listen for match
event which will be fired when a file is found. With each match increase the counter and if it has reached your threshold you can call mg.abort()
to stop the search.
它是一个事件发射器,因此您可以侦听匹配事件,该事件将在找到文件时触发。每次匹配都会增加计数器,如果达到阈值,您可以调用mg.abort()来停止搜索。
#1
3
You can create your own Glob object like this:
您可以像这样创建自己的Glob对象:
var i = 0;
var Glob = require("glob").Glob;
var mg = new Glob(pattern, options, cb);
mg.on("match", function(matched) {
console.log(matched);
i++;
if(i == 5) mg.abort();
});
It is an event emitter so you can listen for match
event which will be fired when a file is found. With each match increase the counter and if it has reached your threshold you can call mg.abort()
to stop the search.
它是一个事件发射器,因此您可以侦听匹配事件,该事件将在找到文件时触发。每次匹配都会增加计数器,如果达到阈值,您可以调用mg.abort()来停止搜索。