How to list files present in a directory using Node.js
Overview
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.
Example
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);}});});
Explanation
- Line 1: We import the
fsmodule to interact with the file system. - Line 2: We import the
pathmodule to get details of the file paths. - Line 3: We create a string variable that contains the directory's path in which the files present should be read.
- Line 6: We use the
readdirmethod to read the files present in the directory. We send a callback function to receive thefilenamesarray as an argument. - Line 7: We use the
forEachmethod to loop the returned filenames by thereaddirmethod. - Line 9: We use the
resolvemethod of the path module to form the current file's absolute path. We then uselstatSyncto synchronously get the information. This information is thefs.Statsobject that contains information about the symbolic link about the resolved path. We then store it in thefileDetailsvariable. - Line 11: We use the
isDirectorymethod to check if the current file is a directory or not. We then print the filename based on this.