Understanding the glob pattern in Node.js
Tags: node
Published: 2022-06-14 17:10:13

**Written by [Frank Joseph](https://blog.logrocket.com/author/frankjoseph/)✏️**

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. 

The glob pattern is most commonly used to specify filenames, called [wildcard character](https://en.wikipedia.org/wiki/Wildcard_character)[s](https://en.wikipedia.org/wiki/Wildcard_character), and strings, called [wildcard matching](https://en.wikipedia.org/wiki/Matching_wildcards). 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

## Table of contents

*   [What is glob matching?](#what-is-glob-matching)
*   [Common glob patterns](#common-glob-patterns)
*   [Setting up our project](#setting-up-our-project)
*   [Navigating through the computer directory](#navigating-through-the-computer-directory)

## 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:

```bash
npm init -y
```

Next, we’ll [install the glob package](https://www.npmjs.com/package/glob) with the following command:

```bash
npm install glob
```

![Glob Dependency Package Json](https://blog.logrocket.com/wp-content/uploads/2022/06/glob-dependency-package-json.png)

Your <code>package.json</code> 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, <code>glob.js</code> and <code>log.js</code>:

![Glob Js Log Js File](https://blog.logrocket.com/wp-content/uploads/2022/06/glob-js-log-js-file.png) 

Add the following code in your `glob.js` file:

```javascript
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](https://blog.logrocket.com/wp-content/uploads/2022/06/glob-files-structure.png) 

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:

```javascript
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](https://blog.logrocket.com/wp-content/uploads/2022/06/print-json-files-console.png)

## 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. 

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

```javascript
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](https://blog.logrocket.com/wp-content/uploads/2022/06/changing-file-path-step-back.png) 

The image below shows the outcome of the command: ![Change File Path Output](https://blog.logrocket.com/wp-content/uploads/2022/06/change-file-path-output.png) 

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

```javascript
node glob
```

![Run Node App Terminal](https://blog.logrocket.com/wp-content/uploads/2022/06/run-node-app-terminal.png) 

The result of running the code above is in the image below: ![Run Node Terminal Result](https://blog.logrocket.com/wp-content/uploads/2022/06/run-node-terminal-result.png) 

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:

```javascript
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](https://nodejs.dev/learn/the-nodejs-fs-module) 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:

```javascript
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](https://blog.logrocket.com/wp-content/uploads/2022/06/read-files-node-js-glob.png) ![Package Lock Json Glob Output](https://blog.logrocket.com/wp-content/uploads/2022/06/package-lock-json-glob-output.png)

## 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!

---
##200’s only :heavy_check_mark: 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.](https://logrocket.com/signup/)

[![LogRocket Sign Up](https://blog.logrocket.com/wp-content/uploads/2019/12/network-request-filter-2-1.png)](https://logrocket.com/signup/)

[LogRocket](https://logrocket.com/signup/) is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.