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: error and data.

Example

Let’s try to read a file and print its content in the console. In the code snippet below, we have two files:

  1. demo.txt: Text file with string data Hey, Hello.

  2. index.js: File containing node.js code to read data from the file demo.txt

index.js
demo.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 fs module and create an object of it.

  • In line 3, we use fs.readFile() method to read file by passing 3 parameters:

    1. demo.txt : Full path or name of file.

    2. utf8: This parameter is used for encoding the data we are reading.

    3. callback(err,data): After the completion of readFile(), it will either return data from the file or throw an error which is then passed to the callback.

  • In line 4, (inside the callback) we have an if condition to check whether error is thrown by readFile() 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 of demo.txt in 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.

Free Resources