How to Read a File in NodeJS

How to Read a File in NodeJS

Node js read file example; In this tutorial, You will learn how to read file (text, HTML, etc) from the system server using node js. And as well as, This tutorial provides you to the example of reading file data in asynchronous (non-blocking) and synchronous (blocking).

You can read a file in NodeJS using fs module. And can read file in synchronous and asynchronous mode using readFile() and readFileSync() methods.

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 Read File Functions

There are two functions to read files in the node js. First function readFile() and another function is readFileSync(). The first function reads the data of the file asynchronous. 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 in 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');

Note:- Both fs.readFile () and fs.readFileSync () read the entire contents of the given files into memory before returning data.

Recommended Node JS Tutorials


My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *