What is the best way to list all file names in a directory using Node.js?
I’m trying to retrieve a list of all file names present in a directory using Node.js. I want the output to be an array of filenames.
What are the built-in methods to achieve Nodejs list files in directory, and how can I implement them efficiently?
             
            
              
              
              
            
           
          
            
            
              The fs.readdirSync() method reads the contents of a directory and returns an array of file names (including subdirectories). It’s a synchronous operation.
const fs = require('fs');
const path = './your-directory'; // specify your directory path
try {
  const files = fs.readdirSync(path); // returns an array of filenames
  console.log(files);
} catch (err) {
  console.error('Error reading directory:', err);
}
Advantages:
- Simple and easy to use.
 
- Blocks execution until the directory is fully read (synchronous).
 
Disadvantages:
- It may not be efficient for large directories due to blocking.
 
             
            
              
              
              
            
           
          
            
            
              The fs.readdir() method reads the contents of a directory asynchronously. It’s recommended when you want non-blocking operations.
const fs = require('fs');
const path = './your-directory'; // specify your directory path
fs.readdir(path, (err, files) => {
  if (err) {
    console.error('Error reading directory:', err);
  } else {
    console.log(files); // prints array of filenames
  }
});
Advantages:
- Non-blocking and efficient for larger directories.
 
- Works well with callback functions and asynchronous flows.
 
Disadvantages:
- Requires a callback, which might be less readable for complex operations.
 
             
            
              
              
              
            
           
          
            
            
              Using fs.promises.readdir() with Promises (Asynchronous)
If you prefer promises (for async/await), the fs.promises.readdir() method is a modern approach to reading directory contents.
const fs = require('fs').promises;
const path = './your-directory'; // specify your directory path
async function listFiles() {
  try {
    const files = await fs.readdir(path); // returns a promise that resolves to an array of filenames
    console.log(files);
  } catch (err) {
    console.error('Error reading directory:', err);
  }
}
listFiles();
Advantages:
- 
More readable and maintainable with async/await.
 
- 
Non-blocking and efficient.
Disadvantages:
 
- 
Requires using promises and async/await, which could be an additional learning curve.