Skip to content
Related Articles

Related Articles

Node.js filehandle.close() Method

Improve Article
Save Article
Like Article
  • Last Updated : 29 Jun, 2020

The filehandle.close() method is used to asynchronously close the given file descriptor thereby clearing the file that is associated with it. This will allow the file descriptor to be reused for other files. 

Calling filehandle.close() method on a file descriptor while some other operation is being performed on it may lead to undefined behavior.

Syntax:

filehandle.close();

Parameters: This method does not accept any parameters.

Example: This example represents the opening of a file and to close the file descriptor.

Note: The “input.txt” should be present in the directory with the following text:

Greetings from GeeksforGeeks

Filename: app.js




// Node.js program to demonstrate the   
// filehandle.close() Method
  
// Import the filesystem module  
const fs = require('fs');
const fsPromises = fs.promises;
  
async function readThenClose() {
    let filehandle = null;
  
    try {
        // Using the filehandle method 
        filehandle = await fsPromises
                .open('input.txt', 'r+');
  
        var data = await filehandle
                .readFile("utf8");
                  
        console.log(data);
  
        filehandle.close();
        console.log("File Closed!");
  
    } catch (e) {
        console.log("Error", e);
    }
}
  
readThenClose().catch((error) => {
    console.log("Error", error)
});

Run app.js file using the following command:

node app.js

Output:

Greetings from GeeksforGeeks
File Closed!

Reference: https://nodejs.org/api/fs.html#fs_filehandle_close

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!