Open In App

Node.js fsPromises.readFile() Method

The fsPromises.readFile() method is used to read the file. This method read the entire file into the buffer. To load the fs module, we use require() method. It Asynchronously reads the entire contents of a file.

Syntax:



fsPromises.readFile( path, options )

Parameters: The method accepts two parameters as mentioned above and described below:

Return Value: It returns a Promise.



The below examples illustrate the fsPromises.readFile() method in Node.js:

Create a demo text file like, we have created GFG.txt with the following text:

Greetings from GeeksforGeeks

Filename: index.js 




// Node.js program to demonstrate
// the fsPromises.readFile() method
 
// Include fs module
const fs = require('fs');
const fsPromises = require('fs').promises;
 
// Use fsPromises.readFile() method
// to read the file
fs.promises.readFile("./GFG_Test.txt")
    .then(function (result) {
        console.log("" + result);
    })
    .catch(function (error) {
        console.log(error);
    })

Step to run this program: Run the following command from the root directory as shown below:

node index.js

Output:

Greetings from GeeksforGeeks

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

Article Tags :