We can use the readdir
method in the fs
module to read all the files present in the directory.
This is an asynchronous method. In the callback function, it has an array containing file and directory names in the specified directory.
The code below demonstrates how to list all the files present in a directory using Node.js:
const fs = require('fs');const path = require('path');const directory = './';// use readdir method to read the files of the direcotyfs.readdir(directory, (err, files) => {files.forEach(file => {// get the details of the filelet fileDetails = fs.lstatSync(path.resolve(directory, file));// check if the file is directoryif (fileDetails.isDirectory()) {console.log('Directory: ' + file);} else {console.log('File: ' + file);}});});
fs
module to interact with the file system.path
module to get details of the file paths.readdir
method to read the files present in the directory. We send a callback function to receive the filenames
array as an argument.forEach
method to loop the returned filenames by the readdir
method.resolve
method of the path module to form the current file's absolute path. We then use lstatSync
to synchronously get the information. This information is the fs.Stats
object that contains information about the symbolic link about the resolved path. We then store it in the fileDetails
variable.isDirectory
method to check if the current file is a directory or not. We then print the filename based on this.