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

Node.js fs.readdirSync() Method

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

The fs.readdirSync() method is used to synchronously read the contents of a given directory. The method returns an array with all the file names or objects in the directory. The options argument can be used to change the format in which the files are returned from the method.

Syntax:

fs.readdirSync( path, options )

Parameters: This method accept two 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’.

Returns: It returns an array of String, Buffer or fs.Dirent objects that contain the files in the directory.

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

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




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


Output:

Current directory filenames:
CONTRUBUTIONS.txt
index.html
index.js
package.json
README.md

Current directory files:
Dirent { name: 'CONTRUBUTIONS.txt', [Symbol(type)]: 1 }
Dirent { name: 'index.html', [Symbol(type)]: 1 }
Dirent { name: 'index.js', [Symbol(type)]: 1 }
Dirent { name: 'package.json', [Symbol(type)]: 1 }
Dirent { name: 'README.md', [Symbol(type)]: 1 }

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




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


Output:

Filenames with the .md extension:
README.md

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



Previous Article
Next Article

Similar Reads

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
Node.js http.IncomingMessage.method Method
The http.IncomingMessage.method is an inbuilt application programming interface of class Incoming Message within the inbuilt http module which is used to get the type of request method as a string. Syntax: request.method Parameters: This method does not accept any argument as a parameter. Return Value: This method returns the request type name as a
2 min read
Node.js URLSearchParams.has() Method
In URLSearchParams interface, the has() method returns a Boolean which tells us that if the parameter with input name exists it will return true, else false. Syntax: var Bool = URLSearchParams.has(name) Returns: True - if name present, else it will return False. Parameters: name - Input the name of the parameter. Example1: let url = new URL('https:
1 min read
Node.js hmac.update() Method
The hmac.update() method is an inbuilt method of class HMAC within the crypto module which is used to update the data of hmac object. Syntax: hmac.update(data[, inputEncoding])Parameters: This method takes the following two parameters: data: It can be of string, Buffer, TypedArray, or DataView type. It is the data that is passed to this function.in
2 min read
three90RightbarBannerImg