Home » Node.js

How do I read a file in node.js using readFile?

In this article, we are going to learn how to read al content of a file using readFile in Node.js?
Submitted by Manu Jemini, on November 17, 2017

Most of the time we request to node for data manipulation via listeners from an html page, but node gives us a module known as File system (fs) by which we can write or show our content of html on browser with particular listeners.

So, in this tutorial we are going to learn fs module in Node.js.

File system (fs) module

fs module in Node.js used to work on the files of our systems and manipulate their data. By using the property .readFile() of file system we can easily fetch any file from our local system and show their data on browser by using res.write() function.

Server file

//step 1
var http = require('http');
var fs = require('fs');
//step 2
http.createServer(function (req, res) {
fs.readFile('demofile.html', function(err, data) {
//step 3
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    res.end();
  });
//listen on port 8080
}).listen(8080);

Here we have come up with a very fundamental server in express.js.

  • We need to require http module from node modules and store its reference in variable http.
  • Then require fs module from node modules and store its reference in variable fs.
  • Now, define http.createServer() method and execute function.
  • Then use fs.readFile() method to fetch file and execute a function with data.
  • Fifth, step is to use writeHead() to write response head.
  • Then, we will write data on browser from file we’d fetched by using write() method and end the response by calling res.end().

HTML File

<html>
	<body>
		<h1>I love IncludeHelp</h1>
	</body>
</html>

Note: Please put html file and server file at same place.

To run server file, you just need to save it by a random name and then open command, type node and file name.

How do I read a file in node.js using readFile

How do I read a file in node.js using readFile

Happy Coding



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.