How to Use fs.readdir in Node.js to Read Directory Contents
Use
fs.readdir in Node.js to read the contents of a directory asynchronously by passing the directory path and a callback function that receives an error and an array of file names. Alternatively, use fs.promises.readdir with async/await for cleaner code.Syntax
The fs.readdir function reads the contents of a directory asynchronously.
path: The folder path to read.options: Optional settings like encoding or withFileTypes.callback: Function called with error and list of files.
Example: fs.readdir(path, options, callback)
javascript
fs.readdir(path, options, callback)
Example
This example shows how to read the files inside the current directory using fs.readdir with a callback, and also how to use the promise version with async/await.
javascript
import fs from 'fs'; // Using callback fs.readdir('.', (err, files) => { if (err) { console.error('Error reading directory:', err); return; } console.log('Files in current directory:', files); }); // Using promises with async/await async function listFiles() { try { const files = await fs.promises.readdir('.'); console.log('Files with promises:', files); } catch (err) { console.error('Error reading directory with promises:', err); } } listFiles();
Output
Files in current directory: ["file1.js","file2.txt","folder"]
Files with promises: ["file1.js","file2.txt","folder"]
Common Pitfalls
Common mistakes include:
- Not handling errors in the callback, which can crash your app.
- Using
fs.readdirSyncin async code, which blocks the event loop. - Forgetting to use the correct path or relative vs absolute paths.
- Not using
awaitwithfs.promises.readdir, causing unhandled promises.
javascript
import fs from 'fs'; // Wrong: ignoring error fs.readdir('.', (err, files) => { if (err) { console.error('Error:', err); return; } console.log(files); }); // Right: handle error fs.readdir('.', (err, files) => { if (err) { console.error('Error:', err); return; } console.log(files); });
Quick Reference
Tips for using fs.readdir:
- Use
fs.promises.readdirwith async/await for cleaner code. - Pass
{ withFileTypes: true }option to getDirentobjects for file type info. - Always handle errors in callbacks or try/catch with promises.
- Use absolute paths to avoid confusion.
Key Takeaways
Use fs.readdir(path, callback) to read directory contents asynchronously with error handling.
Prefer fs.promises.readdir with async/await for modern, cleaner asynchronous code.
Always handle errors to prevent crashes when reading directories.
Use the withFileTypes option to get detailed file info if needed.
Avoid blocking the event loop by not using synchronous directory reads in async code.