In Node.js, you can use the fs.readdir() method to list all files available in a directory. This method works asynchronously to read the contents of the given directory and returns an array of the names of the files in the directory excluding . and ...

Here is an example that reads all files available in a directory and prints their names on the console:

const fs = require('fs');

// directory path
const dir = './node_modules/';

// list all files in the directory
fs.readdir(dir, (err, files) => {
    if (err) {
        throw err;
    }

    // files object contains all files names
    // log them on console
    files.forEach(file => {
        console.log(file);
    });
});

The fs.readdir() method will throw an error if the given directory doesn't exist.

The fs module also provides a synchronous variant of readdir() called readdirSync() that works synchronously and returns an array of the names of the files:

const fs = require('fs');

// directory path
const dir = './node_modules/';

// list all files in the directory
try {
    const files = fs.readdirSync(dir);

    // files object contains all files names
    // log them on console
    files.forEach(file => {
        console.log(file);
    });

} catch (err) {
    console.log(err);
}

Take a look at this guide to learn more about reading and writing files in a Node.js application.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.