How to List Files in a Directory Using Node.js
In Node.js, you can list files in a directory using the
fs.readdir method for asynchronous reading or fs.readdirSync for synchronous reading. These methods return an array of file names inside the specified directory path.Syntax
The fs module provides two main methods to list files in a directory:
fs.readdir(path, callback): Asynchronously reads the contents of a directory.fs.readdirSync(path): Synchronously reads the contents of a directory.
Here, path is the directory path as a string. The asynchronous method uses a callback with error and files array parameters.
javascript
import fs from 'fs'; const path = '.'; // Define the directory path // Asynchronous fs.readdir(path, (err, files) => { if (err) throw err; console.log(files); }); // Synchronous const files = fs.readdirSync(path); console.log(files);
Example
This example shows how to list all files in the current directory asynchronously and synchronously.
javascript
import fs from 'fs'; const directoryPath = '.'; // current directory // Asynchronous listing fs.readdir(directoryPath, (err, files) => { if (err) { console.error('Error reading directory:', err); return; } console.log('Asynchronous file list:', files); }); // Synchronous listing try { const filesSync = fs.readdirSync(directoryPath); console.log('Synchronous file list:', filesSync); } catch (err) { console.error('Error reading directory synchronously:', err); }
Output
Asynchronous file list: ["file1.js", "file2.txt", "folder"]
Synchronous file list: ["file1.js", "file2.txt", "folder"]
Common Pitfalls
Common mistakes when listing files in Node.js include:
- Not handling errors from
fs.readdirorfs.readdirSync, which can crash your program if the directory doesn't exist or permission is denied. - Using synchronous methods in performance-critical or server environments, which blocks the event loop.
- Confusing the directory path; relative paths depend on where the script runs.
javascript
import fs from 'fs'; // Wrong: ignoring errors fs.readdir('wrong/path', (err, files) => { if (err) { console.error('Error reading directory:', err); return; } console.log(files); }); // Right: handle errors fs.readdir('wrong/path', (err, files) => { if (err) { console.error('Failed to read directory:', err.message); return; } console.log(files); });
Quick Reference
Summary of key methods to list files in Node.js:
| Method | Description | Usage |
|---|---|---|
| fs.readdir(path, callback) | Asynchronously reads directory contents | fs.readdir('./folder', (err, files) => { }) |
| fs.readdirSync(path) | Synchronously reads directory contents | const files = fs.readdirSync('./folder') |
Key Takeaways
Use fs.readdir for non-blocking asynchronous directory reading.
Use fs.readdirSync only for simple scripts or startup tasks to avoid blocking.
Always handle errors when reading directories to prevent crashes.
Relative paths depend on the script's running location; use absolute paths if needed.
The methods return an array of file and folder names inside the directory.