Explain Codes LogoExplain Codes Logo

How do you get a list of the names of all files present in a directory in Node.js?

javascript
file-system
async-programming
promises
Anton ShumikhinbyAnton Shumikhin·Nov 3, 2024
TLDR

Quickly fetch all file names from a directory in Node.js using either fs.readdirSync for a synchronous approach or fs.readdir for handling operations asynchronously. Both methods are integral parts of the built-in fs module.

Synchronous example:

const fs = require('fs'); console.log(fs.readdirSync('/path/to/directory')); // Quick'n'dirty

Asynchronous example:

const fs = require('fs'); fs.readdir('/path/to/directory', (err, files) => console.log(files)); // No rush, right?

Take note that these methods simply return the file names, not their full paths or any specific details. Moreover, correct handling of the err parameter is pivotal to manage potential errors in the asynchronous version.

Deep Dive and Edge Cases

Let's venture on to discover more advanced usage scenarios and address potential edge cases.

File Details Included (Node.js v10.10.0+)

With Node.js version 10.10.0 and onwards, you can use { withFileTypes: true } option with the fs.readdir and fs.readdirSync methods to also get the file details. This is a handy trick to distinguish between files and directories.

const fs = require('fs'); const dir = '/path/to/directory'; // Async with details. Shiny! fs.readdir(dir, { withFileTypes: true }, (err, files) => { files.forEach((file) => { if (!file.isDirectory()) { console.log(file.name); // This ain't no folder. } }); });

Recursive wonders: Directory Traversal

For recursive traversal of subdirectories and listing all files therein, you can roll your own recursive function. Or, you know, use a pre-made package like walk.

Example using recursion with fs:

const fs = require('fs'); const path = require('path'); function listFiles(dir, filelist = []) { fs.readdirSync(dir).forEach(file => { const subpath = path.join(dir, file); if(fs.statSync(subpath).isDirectory()) { filelist = listFiles(subpath, filelist); // Abandon all hope, ye who enter here. } else { filelist.push(subpath); // It's a file, not a secret formula. } }); return filelist; // There's no place like home. } console.log(listFiles('/path/to/directory'));

The Special Agent: Pattern Matching with glob

The glob package is like your pattern-matching secret agent. It helps listing files in a directory that match a specified pattern, say, all JavaScript files.

const glob = require('glob'); glob('/path/to/directory/**/*.js', {}, (err, files) => { if (err) throw err; // Arggh! Plan B! files.forEach(file => console.log(file)); // Just scanning your secret projects. });

Promise-land: Promise-based Alternatives

The util.promisify method or the latest fs.promises API give you access to the Promise-land. Enjoy the Promises when listing files.

const { promisify } = require('util'); const fs = require('fs'); const readdirAsync = promisify(fs.readdir); readdirAsync('/path/to/directory') .then(files => console.log(files)) // Filed successfully! .catch(error => console.error(error)); // Pfft! Didn't want to anyway.

Or using fs.promises directly:

const fs = require('fs').promises; async function listFilesAsync(dir) { try { const files = await fs.readdir(dir); console.log(files); } catch (error) { console.error(error); // Error with a capital E. } } listFilesAsync('/path/to/directory');