We shall learn to read a File in Node.js using Node FS, File System built-in module. A Node.js example program that uses readFile() function is provided.

Read a File in Node.js

Following is a step by step guide to read content of a File in Node.js :

  • Step 1 : Include File System built-in module to your Node.js program
     var fs = require(‘fs‘);
  • Step 2 : Read file using readFile function

    Callback function is provided as an argument to readFile function. When reading the file is completed (could be with or without error), call back function is called with err(if there is an error reading file) and data(if reading file is successful).

  • Step 3 : Create a sample file, say sample.html with some content in it. Place the sample file at the location of node.js example program, which is provided below.

Create following Node.js program to read content of file in Node.js

Run the program using node command in terminal or command prompt :

Conclusion :

In this Node.js TutorialNode FS, we have learnt to read a File in Node.js using File System built-in module. Node.js example program has been provided that uses readFile() function.