Member-only story

How To Read a File in Node JS

Bipsmedium
2 min readNov 29, 2022

--

How To Read a file in Node JS

In this tutorial, you will learn how to read a file in Node JS. To do this, you have to include a built-in module of Node JS known as fs( File System) with the help of require() method as shown below

var fs = require("fs");
fs.readFile("name of the file","encoding","function(err,data))

Please note that the readFile() function contains three parameters

  • the filename that has to be read using Node JS.
  • Encoding defines the type of encoding format of the file that has to be read.
  • The third parameter is a callback function that contains two arguments: err and data. If there is any error in your file then err will hold the error message. On the other hand, the data parameter will hold the contents of the file that has to be read if there is no error.

Also read, the Node JS HTTP server example

Steps to read a file in Node JS with an example

  • Create an HTML file or a text file where the node JS file resides. (Mentioned Below)
  • Put some contents in a file that has to be read.
  • Now, create a Node JS file. (Mentioned Below)
  • Open the command terminal and go to the location where your node JS file is…

--

--

Bipsmedium
Bipsmedium

Written by Bipsmedium

Hi, This is Biplab and I am a PHP laravel developer and other open source technologies. I am here to share my experience with the community.

No responses yet