What is the fs.readFile in node.js?
Method
fs.readFile() is an asynchronous and a very easy to use method for reading files of any type.
Syntax
Let us have a look at the syntax of fs.readFile() method:
fs.readFile(File_Path, Option , callback())
Parameters
Following are the parameters taken by the fs.readFile() method:
File_Path: String representing the full path of file with the name.Option: Encoding type e.g.utf-8.callback: A function with two parameters:erroranddata.
Example
Let’s try to read a file and print its content in the console. In the code snippet below, we have two files:
-
demo.txt: Text file with string dataHey, Hello. -
index.js: File containingnode.jscode to read data from the filedemo.txt
const fs = require('fs')fs.readFile('demo.txt', 'utf8' , (error, data) => {if (error) {console.error(error)return}console.log(data)})
Let’s break down the working of code snippet above:
-
In line 1, we import
fsmodule and create an object of it. -
In line 3, we use
fs.readFile()method to read file by passing 3 parameters:-
demo.txt: Full path or name of file. -
utf8: This parameter is used for encoding the data we are reading. -
callback(err,data): After the completion ofreadFile(), it will either returndatafrom the file or throw anerrorwhich is then passed to the callback.
-
-
In line 4, (inside the callback) we have an
ifcondition to check whethererroris thrown byreadFile()or not. -
In line 5, we are printing the error thrown by
readFile(). -
In line 9, after the successful execution of
readFile(), we are printing the content ofdemo.txtin the console.
Output
When we execute the code snippet above, the output is Hey, Hello. This means we have successfully read the data from the file demo.txt using fs.readFile() in node.js. You can change the content of the demo.txt file and see the resulting output after executing the code snippet.