Find the Files that match a pattern using Node.js

avatar

Borislav Hadzhiev

Last updated: Mar 28, 2022

banner

Photo from Unsplash

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
npm install glob

Now we are able to 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 asterisk ** characters match zero or more directories and subdirectories.

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

You can view all of the other characters with special meaning 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 like:

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.

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.