Skip to content
Related Articles
Open in App
Not now

Related Articles

Node.js fs.Dir.read() Method

Improve Article
Save Article
  • Last Updated : 08 Feb, 2023
Improve Article
Save Article

The fs.Dir.read() method is an inbuilt application programming interface of class fs.Dir within File System module which is used to read the 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.

Below programs illustrates the use of fs.Dir.read() method in Node.js:

Example 1: 
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 (var 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 GFG.js file using the following command: 

node GFG.js

Output:  

Example 2: 
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 (var 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 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
 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!