Node.js fs.Dir.readSync() Method

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

Syntax:

const dir.readSync()

Parameter: This method does not accept any parameter.

Return Value: This method returns the dirent of the directory.

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



Example 1:
Filename: index.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the 
// dir.readSync() method
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);
    
  // Synchronously reading the directory's
  // underlying resource handle
  const dirent = dir.readSync();
  
  // Display the result
  console.log(dirent.name);
}
  
// Catching error
stop('./').catch(console.error);

chevron_right


Run index.js file using the following command:

node index.js

Output:

abcd.cer

Example 2:
Filename: index.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the 
// dir.readSync() method
const fs = require('fs');
    
// Initiating asyn function
async function stop(path) {
   
  let dir = null;
   
  try {
  
  // Creating and initiating directory's
  // underlying resource handle
  dir = await fs.promises.opendir(
      new URL('file:///F:/java/'));
  
  // Synchronously reading the directory's
  // underlying resource handle
  // using readSync() method
  for(var i = 0 ; i <= 3 ; i ++ ) {
    var dirent = dir.readSync();
  
    // Display the result
    console.log(dirent.name);
  }
  
  } finally {
   
    if (dir) { 
  
      // Display the result
      console.log("dir is closed successfully");
  
      // Synchronously closeSyncing the 
      // directory's underlying resource
      // handle
      const promise = dir.closeSync()
    }
  }
}
    
// Catching error
stop('./').catch(console.error);

chevron_right


Run index.js file using the following command:

node index.js

Output:

abcd.cer
cert.cer
certfile.cer
certificate1.cer
dir is closed successfully

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




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.