Monday, November 2, 2015

Serving first HTML with node.js

Last week I have written hello world with node js i.e how to write first javascript file on the server side and how to execute it with node.js

In this tutorial, we will see how to start our own server and throwing first html with it. This is achived in two steps




1. Starting a simple server that listens at some port


I went through the http api of node js and figured out starting a simple server on my local machine.
As we have seen hello world with node.js, similarly create another file server.js and put the below code in it, and execute the node cmd to run it

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end("I am server");
}).listen({
  host: 'localhost',
  port: 9191
});


Now, the server is running, Checkout its output by opening your browser and go to the url http://localhost:9191

You should be able to see a simple text "I am server"


2. Serving html content through nodejs server


Now, create another file called hello.html and put basic h1 tag in it like this

<html>
<body>
<h1>HELLO WORLD NODE SERVER </h1>
</body>
</html>


Simple step that we have to do is to read that file and output the file content, for that we need a file system module, use require('fs') to include it

Read the html that we have created using fs.readFile() and put the content in our response.

var http = require('http');
var fs   = require('fs');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  var d = "";

fs.readFile('C://nodeapp/hello.html', {
  encoding: "UTF-8"

}, function (err, data) {
    if (err) throw err;
     d = data;
     //console.log(d);
     res.end(d);
 });
}).listen({
  host: 'localhost',
  port: 9191

});


Now, checkout the browser, it will show you the plain html content (unformattted one), it is becuase our server is responding as text/plain.

Replace text/plain with text/html

Run the app again and open the browser with http://localhost:9191. Thats it, you are done here..!!

If you have any questions, please comment.. Thanks..!!


No comments:

Post a Comment