Last updated: Apr 5, 2024
Reading timeยท3 min
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.
# ๐๏ธ with NPM npm install glob # ๐๏ธ with YARN yarn add glob
Now we can import and use the glob
function.
// ๐๏ธ 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.
// 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.
src
directory that have a .js
extension.You can view all of the other characters with special meanings in the npm page of glob.
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.
The folder structure of the example looks as follows.
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.
You can learn more about the related topics by checking out the following tutorials: