How to use HTML templates in Node.js

In this tutorial I will explain how to use HTML templates in pure Node.js without express. I will work with the files from my last tutorial about Node.js.

At the top of my router file I will add:

var fs = require("fs");

Next, I will replace:

function homepage(request,response) {

if(request.url === "/") {

response.writeHead(200,{"Content-Type":"text/html"});

response.write(" <h2>Hello World!</h2> ");

response.end(); 

}

}

with

function homepage(request,response)
{
if(request.url === "/")
{
fs.readFile("first.html",function(err,data){
response.writeHead(200,{"Content-Type":"text/html"});
response.write(data);
response.end();
});
}
}

Also, I will create a html template, called first.html.

In this way I will render a HTML template in my Node.js project.

Video tutorial:









Leave a Comment