Node.js fs.Dir.read() Method

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node program to demonstrate the 
// dir.path() API
const fs = require('fs');
   
// Intiating asyn 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);

chevron_right


Run GFG.js file using the following command:

node GFG.js

Output:

Example 2:
Filename: GFG.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node program to demonstrate the 
// dir.path() API
const fs = require('fs');
   
// Initiating asyn 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);

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.