Read File in Node.js

We can read a file in Node.js using fs module.

In this tutorial, 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 also provided.

Steps to Read File

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.

fs.readFile('<fileName>',<callbackFunction>)

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.

ADVERTISEMENT

Example 1 – Read File in Node.js

readFileExample.js

// include file system module
var fs = require('fs');

// read file sample.html
fs.readFile('sample.html',
	// 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 terminal or command prompt and run the program using node command.

Output

$ node readFileExample.js
<html>
<body>
<h1>Header</h1>
<p>I have learnt to read a file in Node.js.</p>
</body>
</html>

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.