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

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 9, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/nodejs-find-files-with-pattern-matching

> Learn how to use the glob open-source Node.js module to find all the files that match a certain paterrn.

To find all the files that match a pattern in Node.js:

1. Use and install the `glob` module.
2. Import the `glob` module in your Node.js code.
3. Pass it a pattern as the first parameter and a callback function as the second.
4. The callback function gets called with an error object and a list of matching files.

Open your terminal in the root directory of your Node.js application and type the following command to install `glob`:

```bash
$ npm install glob
```

Now we are ready to use the `glob` module to find files using wild-card pattern matching:

```javascript
const glob = require('glob')

glob('api/**/*.ts', (err, files) => {
  if (err) {
    return console.error(err)
  }

  // Print all files
  console.log(files)
  // ['api/http.ts', 'api/routes.ts', 'api/models/user.ts']

  // Iterate over all files
  files.forEach(file => {
    console.log(file)
  })
})
```

The `glob()` function takes a pattern and a callback function as input parameters. 

The asterisk `*` character matches zero or more characters in a single path portion.

Double asterisk `**` characters match zero or more directories and subdirectories except for symlinked directories.

> The above example matches all files in an `api` directory and its subdirectories with a `.ts` extension.

You can find all other characters with special meaning when used in a path portion on [glob npm page](https://www.npmjs.com/package/glob).
