Find the Files that match a pattern using Node.js

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
3 min

banner

# Find the Files that match a pattern using Node.js

To find the files that match a pattern using Node.js, install and use the glob module, passing it a pattern as the first parameter and a callback function as the second.

The function gets called with a potential error object as the first parameter and the matching files as the second.

Open your terminal in the root directory of your project and install the glob package.

shell
# ๐Ÿ‘‡๏ธ with NPM npm install glob # ๐Ÿ‘‡๏ธ with YARN yarn add glob

Now we can import and use the glob function.

index.js
// ๐Ÿ‘‡๏ธ if using ES6 Imports uncomment next line import {glob} from 'glob'; try { const results = await glob('src/**/*.js'); // [ 'src/file.js', 'src/file-3.js', 'src/file-2.js' ] console.log(results); results.forEach(file => { console.log(file); }); } catch (err) { console.log(err); }

If you use the older, CommonJS syntax, use the following code sample instead.

index.js
// Using the older, CommonJS syntax const {glob} = require('glob'); async function findFiles() { try { const results = await glob('src/**/*.js'); // [ 'src/file.js', 'src/file-3.js', 'src/file-2.js' ] console.log(results); results.forEach(file => { console.log(file); }); return results; } catch (err) { console.log(err); } } findFiles().then(results => { console.log(results); });

The glob library takes a pattern and a callback function as parameters.

The asterisk * character matches 0 or more characters in a single path portion.

Two asterisks ** match zero or more directories and subdirectories.

The example above matches all files in an src directory that have a .js extension.

You can view all of the other characters with special meanings in the npm page of glob.

The callback function gets called with a potential error as the first parameter and the matching files as the second.

If there is no error, then the parameter will have a value of null

The files parameter is an array containing the filenames of the matching files.

Here is an example of running the index.js file from the code snippet above.

find files matching pattern

The folder structure of the example looks as follows.

shell
bobbyhadz-js - index.js - src/ - file-2.js - file-3.js - file.js

I opened my terminal in the same directory as the index.js file and ran it via node index.js.

You can check out more examples of using the glob module on its npm page.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev