Kinda Code
Home/Node/Node.js: Listing Files in a Folder

Node.js: Listing Files in a Folder

Last updated: May 08, 2022

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.