Do you need to list all the files in a folder in Node.js? If so, keep reading to find out how to do it.
There are various ways to achieve this, but one of the best approaches is to use the glob
library. Here’s how you can install it:
npm install glob
Let’s say you want to find all the index.md
files within the content/post
folder, including those in subfolders. For example:
content/post/first/index.md
content/post/second/index.md
content/post/another/test/index.md
To accomplish this, you can use the following code:
const glob = require('glob');
const rootFolder = 'content/post';
glob(rootFolder + '/**/index.md', (err, files) => {
if (err) {
console.log('Error', err);
} else {
console.log(files);
}
});
By executing the above code, you will get an array of all the matching file paths. Feel free to adapt this code according to your specific needs.
Tags: Node.js, file listing, glob