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 me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: