Home Node.js How to Read a File in Node.js using the File System module

How to Read a File in Node.js using the File System module

In this example we show how to read a file in node.js

Following is a basic guide to reading the content of a file in Node.js.

You need to include the File System built-in module into your Node.js program. Like this.

var fs = require('fs');

You then read the file using the readFile() function.

fs.readFile('',)

The Callback function is provided as an argument to thr readFile function.

When the reading of the file is completed, the call back function is called with err and data.

You create a sample file, in this example sample.txt with some content in it. In this example the text file is in the same location as node.js example program

Example

I called the file readfile.js

 

// include file system module
var fs = require('fs');
 
// read the sample text file
fs.readFile('sample.txt',
    // callback function that is called when reading file is done
    function(err, data) {       
        if (err) throw err;
        // data is a buffer containing file content
        console.log(data.toString('utf8'))
});

Open a node.js command prompt and run the program like node readfile.js

This was the output of my file

C:\Users\user\nodejs>node readfile.js
sample text in the file

You may also like