Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-pro· GoogleHugging Face LMArena Human Preference 140K

list files in current directory with nodejs

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with DeepSeekdeepseek-r1-0528’s answer.
  1. User

    list files in current directory with nodejs

  2. Gemini Assistant

    Of course! Here are several ways to list files in the current directory using Node.js, from the most modern and recommended approach to older methods.

    The core module you'll use is the built-in fs (File System) module.

    Summary

    MethodStyleBest ForBlocking?
    fs.promises.readdir()async/awaitMost modern applications, servers.No
    fs.readdir()CallbacksOlder codebases, understanding Node's async nature.No
    fs.readdirSync()SynchronousSimple scripts, command-line tools, startup.Yes

    Method 1: Using async/await with fs.promises (Recommended)

    This is the modern, clean, and preferred way to handle asynchronous operations in Node.js. It's easy to read and avoids "callback hell".

    listFiles.js

    // Import the 'fs/promises' module
    const fs = require('fs/promises');
    const path = require('path');
    
    // Define the directory you want to read. '.' means the current directory.
    const directoryPath = '.';
    
    async function listFiles() {
      try {
        // readdir() returns a promise that resolves to an array of filenames
        const files = await fs.readdir(directoryPath);
        console.log('Files in the current directory:');
        files.forEach(file => {
          console.log(file);
        });
      } catch (err) {
        console.error('Error reading the directory:', err);
      }
    }
    
    // Call the async function
    listFiles();
    

    How to run it:

    1. Save the code as listFiles.js.
    2. Open your terminal in the same folder.
    3. Run the script: node listFiles.js

    Method 2: Using Callbacks (The Classic Asynchronous Way)

    This is the original asynchronous method in Node.js. It's non-blocking, but can lead to nested callbacks ("callback hell") in more complex scenarios.

    listFiles_callback.js

    const fs = require('fs');
    const path = require('path');
    
    const directoryPath = '.';
    
    fs.readdir(directoryPath, (err, files) => {
      // The callback function is executed once the directory reading is complete.
      if (err) {
        console.error('Error reading the directory:', err);
        return;
      }
    
      console.log('Files in the current directory:');
      files.forEach(file => {
        console.log(file);
      });
    });
    
    console.log('This message might appear first, showing it is non-blocking!');
    

    How to run it:

    1. Save the code as listFiles_callback.js.
    2. Run from your terminal: node listFiles_callback.js

    Method 3: Using the Synchronous Method fs.readdirSync()

    This method is simpler to write but blocks the Node.js event loop. This means no other code can execute until the directory is read. It's acceptable for simple scripts or command-line tools, but should be avoided in web servers or other concurrent applications.

    listFiles_sync.js

    const fs = require('fs');
    const path = require('path');
    
    const directoryPath = '.';
    
    try {
      // readdirSync() blocks execution until the result is ready
      const files = fs.readdirSync(directoryPath);
      
      console.log('Files in the current directory:');
      files.forEach(file => {
        console.log(file);
      });
    } catch (err) {
      console.error('Error reading the directory:', err);
    }
    
    console.log('This message will always appear last.');
    

    How to run it:

    1. Save the code as listFiles_sync.js.
    2. Run from your terminal: node listFiles_sync.js

    Bonus: Differentiating Between Files and Directories

    Often, you don't just want the names, you want to know if each item is a file or a directory. You can do this by using fs.stat. Here's how to do it with the recommended async/await approach.

    listFiles_details.js

    const fs = require('fs/promises');
    const path = require('path');
    
    const directoryPath = '.';
    
    async function listFilesWithDetails() {
      try {
        const items = await fs.readdir(directoryPath);
    
        console.log('Contents of the current directory:');
    
        for (const item of items) {
          // We need the full path to get stats
          const fullPath = path.join(directoryPath, item);
          const stats = await fs.stat(fullPath);
    
          if (stats.isDirectory()) {
            console.log(`  - ${item}/  (Directory)`);
          } else {
            console.log(`  - ${item}   (File)`);
          }
        }
      } catch (err) {
        console.error('Error processing directory:', err);
      }
    }
    
    listFilesWithDetails();
    

    How to run it:

    1. Save the code as listFiles_details.js.
    2. Run from your terminal: node listFiles_details.js

    This will give you a more detailed output, similar to what you might see from a command-line ls command.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.