The Wayback Machine - https://web.archive.org/web/20240713015151/https://www.geeksforgeeks.org/node-js-fs-readdir-method/
Open In App

Node.js fs.readdir() Method

Last Updated : 11 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The fs.readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory. The options argument can be used to change the format in which the files are returned from the method.

Syntax:

fs.readdir( path, options, callback )

Parameters: This method accept three parameters as mentioned above and described below:

  • path: It holds the path of the directory from where the contents have to be read. It can be a String, Buffer or URL.
  • options: It is an object that can be used to specify optional parameters that will affect the method. It has two optional parameters:
    • encoding: It is a string value which specifies which encoding would be used for the filenames given to the callback argument. The default value is ‘utf8’.
    • withFileTypes: It is a boolean value which specifies whether the files would be returned as fs.Dirent objects. The default value is ‘false’.
  • callback: It is the function that would be called when the method is executed.
    • err: It is an error that would be thrown if the operation fails.
    • files: It is an array of String, Buffer or fs.Dirent objects that contain the files in the directory.

Below examples illustrate the fs.readdir() method in Node.js:

Example 1: This example uses fs.readdir() method to return the file names or file objects in the directory.




// Node.js program to demonstrate the
// fs.readdir() method
  
// Import the filesystem module
const fs = require('fs');
  
// Function to get current filenames
// in directory
fs.readdir(__dirname, (err, files) => {
  if (err)
    console.log(err);
  else {
    console.log("\nCurrent directory filenames:");
    files.forEach(file => {
      console.log(file);
    })
  }
})
  
// Function to get current filenames
// in directory with "withFileTypes"
// set to "true" 
  
fs.readdir(__dirname, 
  { withFileTypes: true },
  (err, files) => {
  console.log("\nCurrent directory files:");
  if (err)
    console.log(err);
  else {
    files.forEach(file => {
      console.log(file);
    })
  }
})


Output:

Current directory filenames:
index.js
package.json
text_file_a.txt
text_file_b.txt

Current directory files:
Dirent { name: 'index.js', [Symbol(type)]: 1 }
Dirent { name: 'package.json', [Symbol(type)]: 1 }
Dirent { name: 'text_file_a.txt', [Symbol(type)]: 1 }
Dirent { name: 'text_file_b.txt', [Symbol(type)]: 1 }

Example 2: This example uses fs.readdir() method to return only the filenames with the “.txt” extension.




// Node.js program to demonstrate the
// fs.readdir() method
  
// Import the filesystem module
const fs = require('fs');
const path = require('path');
  
// Function to get current filenames
// in directory with specific extension
fs.readdir(__dirname, (err, files) => {
  if (err)
    console.log(err);
  else {
    console.log("\Filenames with the .txt extension:");
    files.forEach(file => {
      if (path.extname(file) == ".txt")
        console.log(file);
    })
  }
})


Output:

Filenames with the .txt extension:
text_file_a.txt
text_file_b.txt

Reference: https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback



Previous Article
Next Article

Similar Reads

Node.js fs.promise.readdir() Method
The fs.promise.readdir() method defined in the File System module of Node.js. The file System module is basically to interact with the hard disk of the users computer. The readdir() method is used to read the files and folders names. The fs.promise.readdir() method returns a resolved or rejected promise and hence avoid the callback nesting or callb
2 min read
How to operate callback-based fs.readdir() method with promises in Node.js ?
The fs.readdir() method is defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the user’s computer. The readdir() method is used to read the contents of a directory. The fs.readdir() method is based on callback. Using callback methods leads to a great chance of callback nesting or call
3 min read
PHP | readdir() Function
The readdir() function in PHP is an inbuilt function which is used to return the name of the next entry in a directory. The method returns the filenames in the order as they are stored in the filenamesystem. The directory handle is sent as a parameter to the readdir() function and it returns the entry name/filename on success or False on failure. S
2 min read
Node.js Automatic restart Node.js server with nodemon
We generally type following command for starting NodeJs server: node server.js In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again. node server.js It is a very hectic task for the development process. Nodemon is a package for handling this rest
1 min read
Top 3 Best Packages Of Node.js that you should try being a Node.js Developer
Node.js is an open-source and server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js has its own package manager called NPM( Node Package Manager) which has very useful and incredible libraries and frameworks that makes our life easier as a developer to work with Node.js. The 3 Best Packages of Node.js that you should
4 min read
Javascript Program For Inserting A Node After The N-th Node From The End
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n. Examples: Input : list: 1->3->4->5 n = 4, x = 2 Output : 1->2->3->4->5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10->8
5 min read
Javascript Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
Node.js Connect Mysql with Node app
Node.js is a powerful platform for building server-side applications, and MySQL is a widely used relational database. Connecting these two can enable developers to build robust, data-driven applications. In this article, we'll explore how to connect a Node.js application with a MySQL database, covering the necessary setup, configuration, and basic
2 min read
How to resolve 'node' is not recognized as an internal or external command error after installing Node.js ?
Encountering the error message ‘node’ is not recognized as an internal or external command after installing Node.js can be frustrating, especially when you’re eager to start working on your project. This error usually means that your system cannot find the Node.js executable because the path to it is not set correctly in your system's environment v
2 min read
Node.js Http2ServerRequest.method Method
The Http2ServerRequest.method is an inbuilt application programming interface of class Http2ServerRequest within the http2 module which is used to get the string representation of the request method. Syntax: const request.method Parameters: This method does not accept any argument as a parameter. Return Value: This method returns the string represe
3 min read
three90RightbarBannerImg