Open In App

Node.js fsPromises.readFile() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • path: It holds the name of the file to read or the entire path if stored at another location. It is a string, buffer, URL, or filename.
  • options: It holds the encoding of the file. Its default value is ‘utf8’. It is an object or a string.
    • encoding: It is a String or NULL. Default: null
    • flag: It is a string that supports file system flags. Default: ‘r’.

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 the option is a string, then it specifies the encoding.
  • When the path is a directory, the behavior of fsPromises.readFile() is platform-specific. On macOS, Linux, and Windows, the promise will be rejected with an error. On FreeBSD, a representation of the directory’s contents will be returned.

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 

javascript




// 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


Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads