What is the stream fs.readdir() method in Node.js?

The fs module is a built-in file system module in Node.js that consists of several methods that can be used to access and manipulate files on the operating system. readdir() is one of the file system module’s methods that is used to asynchronously read file names that exist in the specified directory.

Required import

Import the Node.js package, fs, to access files.

const fs = require('fs')

Parameters

The parameters for the fs.readdir() method include directory, condition, and a callback function. We’ve given the syntax and a brief explanation for each parameter below.

fs.readdir(directory, { condition }, (callback) => {});
  • directory: A string that stores the name or path of the directory from which we want to read file names.

  • condition: An object that defines the two optional parameters:  

    • withFileTypes: A Boolean parameter with a default value, false. It returns true if Dirent describes the directory else, false.

    • encoding: A string parameter with a default value, utf8. It specifies the encoding that would be used for the file names given to the callback argument.  

  • callback: A function that is called once the method is executed and returns one of the two cases:

    • err: Throws an error if the method fails to read the data from the file.

    • files: An array that contains the files present in the directory.

Sample code

The code below reads the data in the given directory, prints the files array, and specifies if it is a file or a directory.

Sample code that implements the fs.readdir() method


Code explanation

Line 1: We import the fs module to access files.
Line 4: We add the listed parameters to the readdir() method.
Lines 7–8: We print an error message if the method does not execute successfully.
Line 11: We print the files array that was returned in case of successful execution.
Line 12: A loop that iterates through the files array using the forEach() method.
Lines 15–16: If the file is a directory, we print the file name along with the message 'is a directory'.
Lines 19–20: If the file is not a directory, we print the file name along with the message 'is not a directory'.

Note: Use the isDirectory() method to check if the file is a directory.

Output

The code prints the files array, containing the file names and their type that are present in the testing directory.

Then, it prints the names of the files and specifies whether they are directories or not. For example, file1.txt is a simple text file, so it prints file1.txt is not a directory and since myFolder1 is a folder, so it prints myFolder1 is a directory.

Terminal snippet of the above code
Terminal snippet of the above code

Food for thought

Question

Why does file.txt in myFolder2 not appear on the terminal?

Show Answer

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved