You can use the built-in fs
(file system) module in Node.js to display all files in a directory. Here’s an example of how to achieve this:
const fs = require('fs');
const path = require('path');
const directoryPath = '/path/to/your/directory';
fs.readdir(directoryPath, (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
files.forEach(file => {
const filePath = path.join(directoryPath, file);
console.log(filePath);
});
});
Replace 'path/to/your/directory'
with the actual path of the directory you want to list files from. The readdir
function reads the contents of the specified directory and passes an array of file names to the callback function. For each file, the example code constructs the full file path using path.join()
and then prints it to the console.
Also keep in mind that the code above just lists the immediate files that are in the directory, not the files within subdirectories. In order to list files recursively, you’ll have to implement a recursive function which traverses the subdirectories as well.