Skip to content
Related Articles

Related Articles

Node.js | fsPromises.readFile() Method
  • Last Updated : 12 Jun, 2020
GeeksforGeeks - Summer Carnival Banner

The fsPromises.readFile() method is used to read the file. This method read the entire file into 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 accept 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 other location. It is a string, buffer, URL or a filename.
  • 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
    • flag: It is a string that support 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 options 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.

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :