Node.js filehandle.close() Method

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
});

chevron_right


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

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.