How to Show a File List in a Directory in Node.js

In this tutorial , we will learn about how to show a file list in a NodeJS directory.
Make sure you have installed NodeJS on your device. You can also download it from here Download here.

Steps to list files in NodeJS Directory

Step 1 :

Open Visual studio code and create a new folder.
Initialize the NodeJS project by entering the following command in your terminal

npm init -y

Explanation : This command will generate a ‘package.json’ file with default settings.

Step 2 :

Create a ‘listFiles.js’ JavaScript file which will contain the code to list all the files in the directory.

Write the code:

const fs = require('fs');
const path = require('path');

const directoryPath = 'F:\\Codespeedy';

function listFiles(directoryPath) {
    fs.readdir(directoryPath, (err, files) => {
        if (err) {
            return console.log('Unable to scan directory: ' + err);
        }
        files.forEach(file => {
            console.log(file);
        });
    });
}

listFiles(directoryPath)

Explanation :

  • Import the required modules
    const fs = require('fs');
    const path = require('path');

    ‘fs’ module allows you to interact with the file system and the ‘path’ module provides the utilities to work with the file system.

  • Set the Directory path
    const directoryPath = 'F:\\Codespeedy';

    Specify the directory path from which you want to list the files.

  • Create a function listFiles
    function listFiles(directoryPath) {
        fs.readdir(directoryPath, (err, files) => {
            if (err) {
                return console.log('Unable to scan directory: ' + err);
            }
            files.forEach(file => {
                console.log(file);
            });
        });
    }

    The fs.readdir method takes two arguments , one is directoryPath and the Callback function.
    The Callback function has two parameters , err and files.
    The Callback function checks if there is an error , if so then it prints the error message ‘Unable to scan directory’, If there is no error , then it iterates the loop and print the file name of each.

  • Call the function 
    listFiles(directoryPath);

 

Step 4 :

Run the script by using the following command :

node listFiles.js

Output :

listFiles.js
package.json

Video:

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top