How to find the files that match a pattern using Node.js

A glob is a string of literals and/or wildcards used to match the file path. With this package, you can easily find the files that match a pattern using Node.js.

Let’s see all the methods in detail.

Find the files that match a pattern using Node.js

Setting up our project

First, open your terminal in the root directory of your Node.js application and create a package.json with the following command:

npm init -y

Next, we’ll install the glob package with the following command:

npm install glob

Now, let’s use the module to find files using wildcard pattern matching. Create new files in your Node.js project folder.

GLOB
│   node_modules  
└───src      
     └───image
     └───log.js
     └───fetch.js
     └───styles.css
└───index.js
└───package.json 
└───package-lock.json

Using the glob module

Node.js get recursively all files

Add the following code in your index.js file:

// Import the glob module
const glob = require("glob");

//passed a pattern into the glob function
//The * character matches zero or more characters in a single path portion
//a callback function that returns the result
glob("./src/**/*", (err, files) => {
  if(err){
    console.log(err)
  }
  console.log(files)
}
     

Output: 

//We get an array of all the files and subdirectories of 'src'
[
'./src/images',
'./src/log.js',
'./src/fetch.js',
'./src/styles.css'
]

Node.js get recursively all files including the dot files.

Let’s add a file in the src: src/.env

// Import the glob module
const glob = require("glob");

glob("./src/**/*",{dot: true}, (err, files) => {
  if(err){
    console.log(err)
  }
  console.log(files)
}
     

dot: true before the callback function to enable the reading of the dot files.

Output: 

[
'./src/images',
'./src/log.js',
'./src/fetch.js',
'./src/styles.css',
'./src/.env'
]

Node.js get all files in the public directory with a specific extension.

const glob = require("glob");

glob("./src/**/*.js", (err, files) => {
  if(err){
    console.log(err)
  }
  console.log(files)
}
     

The code above will search through the current directory and subdirectory, then we get an array of files ending in the extension.js and print them to the console.

Output: 

[
'./src/log.js',
'./src/fetch.js'
]

Bonus tricks

Although the glob module simplifies getting files and subdirectories, you don’t want to add a new dependency to your project. You can import the fs module’s method to achieve the same result.

Below examples illustrate the fs.readdirSync() method in Node.js:

// Import the fs module
const fs = require('fs');

// Function to get current filenames in the directory
const testFolder = 'src';

//forEach() used to iterate over items in a given array.
fs.readdirSync(testFolder).forEach(file => {
  console.log(file);
});

fs.readdirSync( path, options ): This method accepts two parameters.

path: can be a String, Buffer, or URL.

options: to affect the method return value – object.

Output: The function returns array elements after iteration.

[
'./src/images',
'./src/log.js',
'./src/fetch.js',
'./src/styles.css',
'./src/.env'
]

Summary

The above examples demonstrate the typical ways of how Node.js gets all files. It is enough to get you started using the glob package in Node.js. Alternatively, you can build a custom module after understanding the modules glob fs.

If you have any questions, please leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *