Node.js | filehandle.readFile() Method

The filehandle.readFile() method is used to asynchronously read the file contents. This method reads the entire file into the buffer. It Asynchronously reads the entire contents of a file.

Syntax:

filehandle.readFile( options )

Parameters: The method accepts single parameter as mentioned above and described below:

  • options: It holds the encoding of file. Its default value is ‘utf8’. It is an object or a string.
    • encoding: It is a String or NULL. Default: null

Return Value: It returns a Promise.

  • The Promise is resolved with the contents of the file. If no encoding is specified using options.encoding, the data is returned as a Buffer object. Otherwise, the data will be a string.
  • If options is a string, then it specifies the encoding.
  • The FileHandle has to support reading.

Example: Read the file contents of the file ‘GFG.txt’ 

Note: ‘GFG.txt’ should be present in the directory with the following text:



GeeksforGeeks - A computer science portal for geeks

Filename: app.js

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Run app.js file using the following command:

node app.js

Output:

GeeksforGeeks - A computer science portal for geeks

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

My Personal Notes arrow_drop_up

Stepping steps of my ownself

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.