VOOZH about

URL: https://blog.logrocket.com/understanding-using-globs-node-js/

โ‡ฑ Understanding the glob pattern in Node.js - LogRocket Blog


2022-06-08
1116
#node
Frank Joseph
115037
๐Ÿ‘ Image

See how LogRocket's Galileo AI surfaces the most severe issues for you

No signup required

Check it out

Using characters as placeholders is a common practice in computer programming. If youโ€™ve ever tried adding multiple files with an extension similar to Git to a directory using the git add *.java command, then youโ€™ve used the glob pattern.

๐Ÿ‘ Node Glob Pattern

The glob pattern is most commonly used to specify filenames, called wildcard characters, and strings, called wildcard matching. The glob pattern adds all files within a directory with the .java extension, while the git add * command will add all files with the exception of those with a dot . at the start of their name in a given directory.

In this article, weโ€™ll explore how to use the glob pattern in Node.js to represent or specify filenames and arbitrary strings. To follow along with this tutorial, youโ€™ll need the following:

  • A basic understanding of Node.js
  • Node.js installed on your machine
  • A code editor, preferably VS Code

๐Ÿš€ Sign up for The Replay newsletter

The Replay is a weekly newsletter for dev and engineering leaders.

Delivered once a week, it's your curated guide to the most important conversations around frontend dev, emerging AI tools, and the state of modern software.

Table of contents

What is glob matching?

Glob matching, or globbing, is a programming approach that entails using wildcards or glob patterns to specify or match filenames or a set of arbitrary strings.

Compared to the glob pattern, regular expression patterns might be more sophisticated. However, a simplified glob pattern can prove useful in some cases and get the job done.

Common glob patterns

* is one of the most commonly supported basic wildcard matching patterns across different programming languages. * matches any character zero or more times, excluding /. It also does not match files with dot . at the start of their name unless specified by the programmer using the dotglob common option.

The ** wildcard pattern matches any character zero or more times, including /. The ? wildcard pattern matches any character once, but it typically does not match a dotfile, a file name with a leading dot ..

Finally, the [abc] wildcard pattern matches specified characters as defined. In this case, a, b, and c. Now that we have an understanding of what a glob is, letโ€™s learn how to implement globbing in Node.js.

Setting up our project

First, weโ€™ll create a new Node.js project. First, 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

๐Ÿ‘ Glob Dependency Package Json

Your package.json file should look like the image above. Now, letโ€™s write a sample code for using the glob package. Create two files in your Node.js project folder, glob.js and log.js:

๐Ÿ‘ Glob Js Log Js File

Add the following code in your glob.js file:

const glob = require(โ€œglobโ€);

glob("*.js", (error, filesWithJs)=>{
 if(error){
 console.log(error)
 }
 console.log(filesWithJs)
}

In the code above, I imported the glob module, then passed a pattern into the glob function and a callback function that returns the result of the pattern in the function.

When you run the code above, a list of files with the extension .js will be printed:

๐Ÿ‘ Glob Files Structure

Depending on the number of .js files you have in your current working directory, your output should look similar to the screenshot above.

Now, letโ€™s see how to navigate the current working directory and subdirectory using the Node.js glob patterns. In the glob.js file where we imported the glob package, write the following code:

function directoryFiles(error, jsonFilesInDirectory){
 return console.log(jsonFilesInDirectory);
}
glob('*../**/*.json', directoryFiles)

The code snippet above will search through the current directory and subdirectory for files ending with .json as their extension, then print them to the console. The output will be an array of files ending with.json. Yours may differ slightly from the image below:

๐Ÿ‘ Print Json Files Console

Navigating through the computer directory

Next, weโ€™ll learn to use the Node.js package to navigate through the computer directory. To access the current directory of a Node.js application, we have two options to choose from, process.cwd() and __dirname.

The process.cwd() method lies in the Node.js global object and provides information about the current working directory of a Node.js process. On the other hand, the __dirname variable returns the directory name of the current module or file.


Over 200k developers use LogRocket to create better digital experiences

๐Ÿ‘ Image
Learn more โ†’

The code snippet below illustrates the difference between process.cwd() and __dirname:

console.log("This is process.cwd", process.cwd());
console.log("This is _dirname", __dirname);

Before you run the code above, navigate a step backwards in your directory with the cd.. command:

๐Ÿ‘ Changing File Path Step Back

The image below shows the outcome of the command:

๐Ÿ‘ Change File Path Output

Go ahead and run your Node.js application with the command below:

 node glob

๐Ÿ‘ Run Node App Terminal

The result of running the code above is in the image below:

๐Ÿ‘ Run Node Terminal Result

Now that we understand the difference between process.cwd() and __dirname, letโ€™s use the process.cwd() function with glob. Weโ€™ll use the following code snippet for illustration:

const glob = require(โ€œglobโ€);

stepInDirectory = {
 cwd: "../"
}
allJSFiles = (error, filesWithJS)=>console.log(filesWithJS);

// add a glob pattern
glob('**/*.js', stepInDirectory, allJSFiles);

console.log("This is an illustration for the current working directory", process.cwd());

So far, weโ€™ve only used the Node.js glob package for globbing, or pattern matching, but the Node.js glob isnโ€™t limited to pattern matching. In collaboration with the Node.js file system package, fs, you can use glob to read files.

The code snippet below illustrates how to use glob and fs in a Node.js application to read files:

const glob = require(โ€œglobโ€);
const fs = require('โ€™fsโ€);

const readFiles = function (pat, forFile) {
 // pattern
 pat = '*.json';
 // for file method
 forFile = (contentOfFile, jsonFileInDirectory) => {
 console.log(' ');
 console.log(jsonFileInDirectory);
 console.log(' ');
 console.log(contentOfFile);
 console.log(' ');
 };
 // using glob
 glob(pat, function (err, files) {
 if (err) {
 console.log(err);
 } else {
 files.forEach(function (file) {
 fs.readFile(file, function (err, data) {
 if (err) {
 console.log(err);
 } else {
 forFile(data.toString(), file);
 }
 });
 });
 }
 });
};
readFiles();

The code examines the current folder for files ending with .json, prints a space, reads the content, and finally prints it to the console. If you have the same code as I have, the output should be similar the to the one below:

๐Ÿ‘ Read Files Node Js Glob

๐Ÿ‘ Package Lock Json Glob Output

Conclusion

In this tutorial, we covered several of the most common glob patterns including *, **, ? , and finally  [abc], considering the differences between wildcard characters and wildcard matching. We demonstrated how globbing can be used in Node.js applications along with fs, another useful Node.js package, to read files in our application.

We also illustrated how to use the glob pattern to traverse our working directory. The lessons from this tutorial should be enough to get you started using the glob package in Node.js, but be sure to leave a comment if you have any questions. Happy coding!

200s only ๐Ÿ‘ Image
Monitor failed and slow network requests in production

Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If youโ€™re interested in ensuring requests to the backend or third-party services are successful, try LogRocket.

๐Ÿ‘ LogRocket Network Request Monitoring

LogRocket lets you replay user sessions, eliminating guesswork around why bugs happen by showing exactly what users experienced. It captures console logs, errors, network requests, and pixel-perfect DOM recordings โ€” compatible with all frameworks.

LogRocket's Galileo AI watches sessions for you, instantly identifying and explaining user struggles with automated monitoring of your entire product experience.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. Start monitoring for free.

๐Ÿ‘ Image
๐Ÿ‘ Image
๐Ÿ‘ Image

Stop guessing about your digital experience with LogRocket

Get started for free

Recent posts:

Debug Next.js apps with AI agents and next-browser

Learn how next-browser gives AI agents runtime context for debugging Next.js apps, including React props, hydration, PPR, forms, and performance.

๐Ÿ‘ Image
Emmanuel John
Jun 17, 2026 โ‹… 9 min read

Stop hardcoding LLM SDKs: Dynamic LLM routing with OpenRouter and Next.js

Build dynamic LLM routing in Next.js with OpenRouter, TanStack AI, task classification, model fallbacks, and cost-aware routing.

๐Ÿ‘ Image
Chizaram Ken
Jun 16, 2026 โ‹… 13 min read

What is TSRX?: What JSX would look like if it were designed today

TSRX adds first-class control flow, conditional hooks, and scoped styles to React via a TypeScript compiler extension โ€” no new framework required.

๐Ÿ‘ Image
Ikeh Akinyemi
Jun 12, 2026 โ‹… 6 min read

How to add authentication to a React Native app with Better Auth

Learn how to build a full React Native auth system using Better Auth and Expo โ€” with email/password login, Google OAuth, session persistence, and protected routes.

๐Ÿ‘ Image
Chinwike Maduabuchi
Jun 9, 2026 โ‹… 13 min read
View all posts

Would you be interested in joining LogRocket's developer community?

Join LogRocketโ€™s Content Advisory Board. Youโ€™ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

Sign up now