Nodejs glob multiple patterns
Asked Answered
C

4

9

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".

Crin answered 28/2, 2020 at 15:49 Comment(1)
What library are you using?Rhodonite
R
10

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)
})
Rhodonite answered 28/2, 2020 at 16:56 Comment(1)
**/(*.tsx|*.ts) doesn't seem to work, I had to do **/*.ts*Elk
V
3

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)
}
Vaquero answered 25/4 at 16:7 Comment(0)
C
2

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}, () => {});
Cordierite answered 24/12, 2021 at 3:59 Comment(0)
C
2

As per this comment you can use {,,,,} syntax for multiple matches:

glob.sync('{abc.pdf,xyz.pdf}')

With wildcards:

glob.sync('{*.js,*.html}')
Christo answered 16/1, 2023 at 16:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.