How do you get a list of the names of all files present in a directory in Node.js?
In Node.js, the fs
(File System) module provides methods to read and manipulate directories. The most common approaches to list file names within a directory are:
1. Using fs.readdir
(Asynchronous)
const fs = require('fs'); const path = require('path'); fs.readdir('/path/to/directory', (err, files) => { if (err) { return console.error('Error reading directory:', err); } // `files` is an array of filenames files.forEach((file) => { const filePath = path.join('/path/to/directory', file); console.log('File:', filePath); }); });
How It Works
fs.readdir
: Reads the directory contents asynchronously, returning an array of file (and subdirectory) names.- Error-First Callback: If an error occurs (e.g., the directory doesn’t exist),
err
will be set. - Iterate: You can loop through the array (
files
) to handle each file. If you need full paths, join them with the directory path usingpath.join
.
2. Using fs.readdirSync
(Synchronous)
const fs = require('fs'); const path = require('path'); try { const files = fs.readdirSync('/path/to/directory'); files.forEach((file) => { const filePath = path.join('/path/to/directory', file); console.log('File:', filePath); }); } catch (err) { console.error('Error reading directory:', err); }
How It Works
fs.readdirSync
: A synchronous version offs.readdir
.- Blocks Execution: The call to
readdirSync
blocks the event loop until the directory contents are read. Use this only if the blocking nature won’t impact performance significantly.
3. Using fs.promises.readdir
(Promises / async-await)
In modern Node.js (v10+), you can use the fs.promises
API for promise-based file operations. This is handy if you prefer async/await syntax:
const fs = require('fs').promises; const path = require('path'); async function listFiles() { try { const files = await fs.readdir('/path/to/directory'); for (const file of files) { const filePath = path.join('/path/to/directory', file); console.log('File:', filePath); } } catch (err) { console.error('Error reading directory:', err); } } listFiles();
How It Works
- Promises:
fs.readdir
fromfs.promises
returns a promise, which you can await. - Async/Await: Provides a more straightforward asynchronous flow, especially when dealing with complex file operations.
4. Distinguishing Between Files and Directories
If you need to filter out subdirectories or perform operations that differ for files vs. directories, you can use fs.stat
or fs.lstat
:
const fs = require('fs'); const path = require('path'); fs.readdir('/path/to/directory', (err, items) => { if (err) throw err; items.forEach((item) => { const itemPath = path.join('/path/to/directory', item); fs.stat(itemPath, (err, stats) => { if (err) throw err; if (stats.isFile()) { console.log(item + ' is a file'); } else if (stats.isDirectory()) { console.log(item + ' is a directory'); } }); }); });
Recommended Resource
Summary
fs.readdir
(callback): Asynchronously reads directory contents.fs.readdirSync
: Synchronous, blocks execution.fs.promises.readdir
: Promise-based approach, ideal with async/await.- Optionally use
fs.stat
orfs.lstat
to determine if an entry is a file, directory, or symbolic link.
These methods let you reliably read directory contents in Node.js and handle them in whichever style (callback, sync, or async/await) fits your application.
CONTRIBUTOR
TechGrind