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
:
$ 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
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.