Home > Article > Web Front-end > How Can I List All Files in a Directory Using Node.js?
Finding All Filenames in a Directory in Node.js
In Node.js, obtaining a list of filenames present in a directory involves utilizing the fs module. The two primary methods for this task are fs.readdir and fs.readdirSync.
fs.readdir
This asynchronous method accepts a directory path and a callback function. When the read process is complete, the callback is invoked with an array containing the filenames found in the directory. Here's an example:
const testFolder = './tests/'; const fs = require('fs'); fs.readdir(testFolder, (err, files) => { if (err) throw err; files.forEach(file => { console.log(file); }); });
fs.readdirSync
Asynchronous, this method operates synchronously. It returns an array of filenames immediately upon completion of the read process. This blocks further execution until the operation finishes. For instance:
const testFolder = './tests/'; const fs = require('fs'); fs.readdirSync(testFolder).forEach(file => { console.log(file); });
Difference Between the Methods
fs.readdir is asynchronous, requiring a callback for execution upon the completion of the read process. This allows other code to run concurrently.
Conversely, fs.readdirSync is synchronous, meaning it executes immediately and halts code execution until the read process is complete.
The above is the detailed content of How Can I List All Files in a Directory Using Node.js?. For more information, please follow other related articles on the PHP Chinese website!