Node.js: Listing Files in a Folder

Updated: May 8, 2022 By: A Goodman Post a comment

In Node.js, you can asynchronously list all files in a certain directory by using fs.promises.

Example

I have a Node.js project with the file structure as follows:

.
├── files
│   ├── a.jpg
│   ├── b.png
│   ├── c.xml
│   ├── d.csv
│   └── example.txt
├── index.js
└── package.json

Here’s the code in index.js:

import fsPromises from 'fs/promises'
// if you prefer commonJS, use this:
// require fsPromises from 'fs/promises'

const listFiles = async (path) => {
    const filenames = await fsPromises.readdir(path);
    for (const filename of filenames){
        console.log(filename);
    }
}   

// Test it
listFiles('./files');  

The output I get when running the code:

a.jpg
b.png
c.xml
d.csv
example.txt

That’s it. Further reading:

You can also check out our Node.js category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles