How to find files that match a pattern using Node.js
To find all the files that match a pattern in Node.js:
- Use and install the glob module.
- Import the glob module in your Node.js code.
- Pass it a pattern as the first parameter and a callback function as the second.
- 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 :
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 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.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
Find files with javascript
Find files or directories by name.
Find all files in current directory.
var find = require('find');find.file(__dirname, function(files)console.log(files.length);>)
Filter by regular expression.
find.file(/\.js$/, __dirname, function(files)console.log(files.length);>)
- Recursively search each sub-directories
- Asynchronously or synchronously
- Filtering by regular expression or string comparing
.file([pattern,] root, callback)
find.file(__dirname, function(files)//>)
find.dir(__dirname, function(dirs)//>)
.eachfile([pattern,] root, action)
find.eachfile(__dirname, function(file)//>)
.eachdir([pattern,] root, action)
find.eachdir(__dirname, function(dir)//>)
var files = find.fileSync(__dirname);
var dirs = find.dirSync(__dirname);
Handling errors in asynchronous interfaces
find.file(__dirname, function(file)//>).error(function(err)if (err)//>>)
Detect end in find.eachfile and find.eachdir
find.eachfile(__dirname, function(file)//>).end(function()console.log('find end');>)
const fs, vol > = require('memfs');const json ='./README.md': '1','./src/index.js': '2'>;vol.fromJSON(json, '/app');find.use( fs: fs >).file('/app', console.log);
Find files with javascript
Find files or directories by name.
Find all files in current directory.
var find = require('find');find.file(__dirname, function(files)console.log(files.length);>)
Filter by regular expression.
find.file(/\.js$/, __dirname, function(files)console.log(files.length);>)
- Recursively search each sub-directories
- Asynchronously or synchronously
- Filtering by regular expression or string comparing
.file([pattern,] root, callback)
find.file(__dirname, function(files)//>)
find.dir(__dirname, function(dirs)//>)
.eachfile([pattern,] root, action)
find.eachfile(__dirname, function(file)//>)
.eachdir([pattern,] root, action)
find.eachdir(__dirname, function(dir)//>)
var files = find.fileSync(__dirname);
var dirs = find.dirSync(__dirname);
Handling errors in asynchronous interfaces
find.file(__dirname, function(file)//>).error(function(err)if (err)//>>)
Detect end in find.eachfile and find.eachdir
find.eachfile(__dirname, function(file)//>).end(function()console.log('find end');>)
const fs, vol > = require('memfs');const json ='./README.md': '1','./src/index.js': '2'>;vol.fromJSON(json, '/app');find.use( fs: fs >).file('/app', console.log);
Find files with javascript
Last updated: Jan 14, 2023
Reading time · 3 min
# Find the Files that match a pattern using Node.js
To find the files that match a pattern using Node.js, install and use the glob module, passing it a pattern as the first parameter and a callback function as the second.
The function gets called with a potential error object as the first parameter and the matching files as the second.
Open your terminal in the root directory of your project and install the glob package.
Copied!# 👇️ with NPM npm install glob # 👇️ with YARN yarn add glob
Now we can import and use the glob function.
Copied!// 👇️ if using ES6 Imports uncomment next line // import glob from 'glob'; const glob = require('glob'); glob('src/**/*.js', function (err, files) if (err) console.log(err); > // 👇️ ['src/file-2.js', 'src/file-3.js', 'src/file.js'] console.log(files); files.forEach(file => console.log(file); >); >);
The glob library takes a pattern and a callback function as parameters.
The asterisk * character matches 0 or more characters in a single path portion.
Two asterisks ** match zero or more directories and subdirectories.
You can view all of the other characters with special meanings in the npm page of glob.
The callback function gets called with a potential error as the first parameter and the matching files as the second.
If there is no error, then the parameter will have a value of null
The files parameter is an array containing the filenames of the matching files.
Here is an example of running the index.js file from the code snippet above.
The folder structure of the example looks as follows.
Copied!bobbyhadz-js - index.js - src/ - file-2.js - file-3.js - file.js
I opened my terminal in the same directory as the index.js file and ran it via node index.js .
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
- Node.js fs.readdirSync() method explained (with examples)
- How to Replace a String in a File using Node.js
- Cannot find module ‘X’ error in Node.js [Solved]
- Get absolute path of file from relative path in Node.js
- Await is only valid in async function error in JS and NodeJS
- List all directories in a directory in Node.js [4 Ways]
- How to get the Number of CPU Cores using Node.js
- Count the number of Files in a Directory using Node.js
- How to Delete all Files in a Directory using Node.js
- Convert an Image or an Image URL to base64 in Node.js
- DeprecationWarning: Buffer() is deprecated due to security and usability issues
- Error: read ECONNRESET issue solved in Node & Postman
- How to create an empty file in Node.js [4 easy Ways]
- How to append data to a File using Node.js [6 Ways]
- How to check if a Directory exists in Node.js [6 Ways]
- How to get the Size of a File in Node.js [5 Ways]
- The «cb» argument must be of type function Received undefined
- Error: secretOrPrivateKey must have a value in Node.js [Fix]
- How to copy a Folder recursively in Node.js
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.