list files in current directory with nodejs
- User
list files in current directory with nodejs
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
Method Style Best For Blocking? fs.promises.readdir()async/awaitMost modern applications, servers. No fs.readdir()Callbacks Older codebases, understanding Node's async nature. No fs.readdirSync()Synchronous Simple scripts, command-line tools, startup. Yes
Method 1: Using
async/awaitwithfs.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:
- Save the code as
listFiles.js. - Open your terminal in the same folder.
- 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.jsconst 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:
- Save the code as
listFiles_callback.js. - 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.jsconst 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:
- Save the code as
listFiles_sync.js. - 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 recommendedasync/awaitapproach.listFiles_details.jsconst 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:
- Save the code as
listFiles_details.js. - 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
lscommand.- Save the code as
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.