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

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:

$ npm install glob

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

const glob = require('glob')

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

  // Print all files
  // ['api/http.ts', 'api/routes.ts', 'api/models/user.ts']

  // Iterate over all files
  files.forEach(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.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.