Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

node.js
communitycreator

How to list files present in a directory using Node.js

Programming Bytes

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 direcoty 
fs.readdir(directory, (err, files) => {
  files.forEach(file => {
    // get the details of the file 
    let fileDetails = fs.lstatSync(path.resolve(directory, file));
    // check if the file is directory 
    if (fileDetails.isDirectory()) {
      console.log('Directory: ' + file);
    } else {
      console.log('File: ' + file);
    }
  });
});
Read all the files present in a directory

Explanation

  • Line 1: We import the fs module to interact with the file system.
  • Line 2: We import the path module 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 readdir method to read the files present in the directory. We send a callback function to receive the filenames array as an argument.
  • Line 7: We use the forEach method to loop the returned filenames by the readdir method.
  • Line 9: We use the 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.
  • Line 11: We use the isDirectory method to check if the current file is a directory or not. We then print the filename based on this.

RELATED TAGS

node.js
communitycreator
RELATED COURSES

View all Courses

Keep Exploring