Node.js | fsPromises.readFile() Method

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

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.