How to Read a File in Node JS?




How to Read a File in Node JS?

Hello Friends,

In this post, we will discuss the the Node JS Platform “fs” module. FS Stands for File System. This module is also known as IO or FileSystem or Stream module.

This article is focused on how to read a file in node js. In this article, we will implement a reading file with node.js. We will look at an example of reading a file in node.js. This tutorial will give you a simple example of a complete guide for reading files in node.js. So, let's follow a few steps to create an example of the ultimate guide to reading files in node.js.

For this tutorial; you need to create a new text file name myfile.txt and update the following text in this file:

myfile.txt file content







Node.js fs.readFile() Method

There are two functions to read files in the node js. The first function readFile() and another part is readFileSync(). The first function reads the data of the file asynchronously. The second function reads the file’s data synchronously.

readFile() function

The readFile() function reads the file’s data asynchronous.


fs.readFile(file[, options], callback)

Example – Node JS Read file asynchronously

var fs = require('fs');

fs.readFile('c:\\myfile.txt', 'utf8', function(error, data) {

if (error) {

console.log('Error:- ' + error);

throw error;




readFileSync() function

The readFileSync() function reads the file’s data Synchronous.


fs.readFileSync(file[, options])

Example – Node JS Read file in synchronously

var fs = require('fs');

var data = fs.readFileSync('c:\\myfile.txt', 'utf8');


I hope it can help you...

#Node JS