The fs.readFile() method is an inbuilt method which is used to read the file. This method read the entire file into buffer. To load the fs module we use require() method. For example: var fs = require('fs');
Syntax:
fs.readFile( filename, encoding, callback_function )
Parameters: The method accept three parameters as mentioned above and described below:
- filename: It holds the name of the file to read or the entire path if stored at other location.
- encoding: It holds the encoding of file. Its default value is ‘utf8’.
- callback_function: It is a callback functiion that is called after reading of file. It takes two parameters:
- err: If any error occured.
- data: Contents of the file.
Return Value: It returns the contents/data stored in file or error if any.
Below examples illustrate the fs.readFile() method in Node.js:
Example 1:
// Node.js program to demonstrate // the fs.readFile() method // Include fs module var fs = require('fs'); // Use fs.readFile() method to read the file fs.readFile('Demo.txt', 'utf8', function(err, data){ // Display the file content console.log(data); }); console.log('readFile called'); |
Output:
readFile called undefined
Explanation: The output is undefined it means the file is null. It starts reading the file and simultaneously executes the code. The function will be called once the file has been read meanwhile the ‘readFile called’ statement is printed then the contents of the file are printed.
Example 2:
// Node.js program to demonstrate // the fs.readFile() method // Include fs module var fs = require('fs'); // Use fs.readFile() method to read the file fs.readFile('demo.txt', (err, data) => { console.log(data); }) |
Output:
undefined
Reference: https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback
Recommended Posts:
- Nodejs | Automatic restart NodeJs server with nodemon
- Nodejs console.timeLog() Method
- Nodejs - Connect MongoDB with Node app using MongooseJS
- Cowsay in Nodejs using Requests library
- Nodejs | Web Crawling using Cheerio
- Web-Socket in NodeJS
- Signup Form Using Nodejs and MongoDB
- Dockerizing a simple Nodejs app
- Nodejs | DNS
- Encrypting Data in NodeJS
- Nodejs | Jimp
- Nodejs – Connect Mysql with Node app
- Nodejs | DNS | setServers()
- NodeJS | Building simple REST API in express
- NodeJs - Handling invalid routes
- Nodejs | authentication using Passportjs and passport-local-mongoose
- Nodejs | GM charcoal() Function
- Nodejs | GM blur() Function
- Nodejs | GM sharpen() Function
- Nodejs | GM drawLine() Function
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.

