goryef
goryef

Reputation: 1489

How to glob multiple patterns in Node.js?

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

Answers (4)

alexloehr
alexloehr

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

Stanley Ulili
Stanley Ulili

Reputation: 1384

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)
}

Upvotes: 4

jakub.g
jakub.g

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

Edgar Huynh
Edgar Huynh

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

Related Questions