Reputation: 1489
Is it possible to include multiple patterns in a single search string in glob
for Node.js?
For example to find all files named *abc*.pdf
and *xyz.pdf*
Upvotes: 10
Views: 11048
Reputation: 1831
When using node-glob you can provide multiple patterns like this:
"*(pattern1|pattern2|...)"
Which would translate in your example like:
"*(abc.pdf|xyz.pdf)"
Full example to find all .html
and .js
files in the current directory:
glob("*(*.js|*.html)", {}, function (err, files) {
console.log(files)
})
Upvotes: 11
Reputation: 1384
If you have Node.js 22 or higher, you don't need to use the node-glob package to use glob
. The fs
module ships with glob
and globSync
.
Building upon alexloehr answer, you can use glob
natively like this:
import { glob } from 'node:fs/promises';
for await (const entry of glob("*(*.js|*.html)")){
console.log(entry)
}
Upvotes: 4
Reputation: 41378
As per this comment you can use {,,,,}
syntax for multiple matches:
glob.sync('{abc.pdf,xyz.pdf}')
With wildcards:
glob.sync('{*.js,*.html}')
Upvotes: 2
Reputation: 181
For who want a glob options with recursive matching with multiple file extension. This will match all file within the path
folder that has extension .ts?x
and .js?x
.
import * as glob from "glob";
// Synchronous operation
glob.sync(`path/**/*(*.ts|*.tsx|*.js|*.jsx)`, {...globOptions});
// Asynchronous operation
glob(`path/**/*(*.ts|*.tsx|*.js|*.jsx)`, {...globOptions}, () => {});
Upvotes: 2