Open In App

Node.js fs.Dir.close() Method

Last Updated : 02 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The fs.Dir.close() method is an inbuilt application programming interface of class fs.Dir with in File System module which is used to close the directory’s underlying resource handle asynchronously.

Syntax: 

const dir.close()

Parameter: This method does not accept any parameter.
Return Value: This method returns the promise which is just an enhancement to callback functions stop().

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

Example 1:

Filename: GFG.js 

Javascript




// Node program to demonstrate the
// dir.close() method
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);
   
  // Asynchronously closing the directory's
  // underlying resource handle
  const promise = dir.close();
 
  // Display the result
  console.log(promise);
}
 
// Catching error
stop('./').catch(console.error);


Run GFG.js file using the following command: 

node GFG.js

Output:  

Example 2:  

Javascript




// Node program to demonstrate the
// dir.close() API
const fs = require('fs');
 
// Initiating async 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/'));
 
  } finally {
 
    if (dir) {
 
      // Display the result
      console.log("dir is closed successfully");
  
      // Close the file if it is opened.
      await dir.close();
    }
  }
}
 
// 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_close
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads