Node js Read File Example
Node Js 10-Mar-2021

Node js Read File Example

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

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.

First of all, you need to create a new text file name myfile.txt and update the following text in this file:

myfile.txt file content

 php
 java
 nodejs
 javascript
 ruby
 python

Node Js Read File Functions

readFile() function

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

syntax

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;
    }
    console.log(data);
});

readFileSync() function

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

syntax

fs.readFileSync(file[, options])

Example – Node JS Read file in synchronously

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

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