Open In App
Related Articles

Node.js fs.Dir.read() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The fs.Dir.read() method is an inbuilt application programming interface of class fs.Dir within File System module which is used to read each next directory (dirent) one by one asynchronously.

Syntax: 

const fs.Dir.read(callback)

Parameter: This method takes a callback function as a parameter that has the following arguments.  

  • err: if any error occurred.
  • dirent: dirent of the directory after reading.

Return Value: This method does not return any value.

Example 1: The below program illustrates the use of fs.Dir.read() method in Node.js

Filename: GFG.js 

Javascript

// Node program to demonstrate the
// dir.read() API
const fs = require('fs');
 
// Initiating async function
async function stop(path) {
 
    // Creating and initiating directory's
    // underlying resource handle
    const dir = await fs.promises
        .opendir(new URL('file:///F:/'));
 
    // Getting all the dirent of the directory
    for (let i = 1; i <= 2; i++) {
 
        // Reading each dirent one by one
        // by using read() method
        dir.read((err, dirent) => {
 
            // Display each dirent one by one
            console.log(`${dirent.name}
    ${err ? 'does not exist' : 'exists'}`);
        });
    }
}
 
// Catching error
stop('./').catch(console.error);

                    

Run the GFG.js file using the following command: 

node GFG.js

Output:  

Example 2: The below program illustrates the use of fs.Dir.read() method in Node.js 

Filename: GFG.js  

Javascript

// Node program to demonstrate the
// dir.read() API
const fs = require('fs');
 
// Initiating async function
async function stop(path) {
 
    // Creating and initiating directory's
    // underlying resource handle
    const dir = await fs.promises.opendir(path);
 
    // Getting all the dirent of the directory
    for (let i = 1; i <= 4; i++) {
 
        // Reading each dirent one by one
        // by using read() method
        dir.read((err, dirent) => {
 
            // Throwing error
            if (err) throw err
 
            // Display each dirent one by one
            console.log(dirent.name);
        });
    }
}
 
// Catching error
stop('./').catch(console.error);

                    

Run the GFG.js file using the following command: 

node GFG.js

Output:  

Note: The above program will not run on online JavaScript and script editor.

Reference: https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_dir_read_callback



Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads