Find the Files that match a pattern using Node.js

avatar
Borislav Hadzhiev

Last updated: Jan 14, 2023
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'; const glob = require('glob'); glob('src/**/*.js', function (err, files) { if (err) { console.log(err); } // ๐Ÿ‘‡๏ธ ['src/file-2.js', 'src/file-3.js', 'src/file.js'] console.log(files); files.forEach(file => { console.log(file); }); });

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.

# 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