a blog for those who code

Tuesday, 24 June 2014

Loading HTML in NodeJS

In this post I will explain you how to load HTML pages in NodeJS. In this site you can check how to create a Node JS static file in web server.

Now when I have created a static page I want an initial html page to load instead of plain text. So for that we will create a sample html index page which will load up on starting our server.

We will modify the existing code itself so the code,

fs.readFile(filename, "binary", function(err, file) {
      if(err) {      
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      response.writeHead(200);
      response.write(file, "binary");
      response.end();
    });

Source : https://gist.github.com/rpflorence/701407

will become...

fs.readFile(filename, "binary", function(err, file) {
      if(err) {      
        response.writeHead(500, {"Content-Type": "text/html"});
        response.write(err + "\n");
        response.end();
        return;
      }

      response.writeHead(200, {"Content-Type": "text/html"});
      response.write(file);
      response.end();
    });
So using the above code we can easily load html in NodeJS.

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License