Is it possible to include multiple patterns in a single search string in glob for nodejs? Like i need to find all files that have "abc.pdf" and "xyz.pdf".
Nodejs glob multiple patterns
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 (find all .html and .js files in current directory):
glob("*(*.js|*.html)", {}, function (err, files) {
console.log(files)
})
**/(*.tsx|*.ts)
doesn't seem to work, I had to do **/*.ts*
–
Elk Update as of 2024
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)
}
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}, () => {});
As per this comment you can use {,,,,}
syntax for multiple matches:
glob.sync('{abc.pdf,xyz.pdf}')
With wildcards:
glob.sync('{*.js,*.html}')
© 2022 - 2024 — McMap. All rights reserved.