Node JS Tutorial | HTTP Server Basic HTML Templates

Node JS Tutorial | HTTP Server Basic HTML Templates REPL Here

Today we are adding a basic HTML template to our Node JS HTTP Server project.

We are going to first require the file system module within Node.


1
var fs = require('fs');

Lets create a .html file named index.html


1
2
3
4
fs.open('index.html', 'w', function (err, file) {
  if (err) throw err;
  console.log('Saved!');
});

Now append some HTML


1
2
3
4
fs.appendFile('index.html', '<html><body><h1>HELLO WORLD</h1></body></html>', function (err) {
  if (err) throw err;
  console.log('APPENDING INDEX.HTML FILE');
});

Then we open the index.html file and pass that as an argument into the server response to render.


1
2
3
4
5
6
7
8
9
10
fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err;
    }      
    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(8000);
});

https://stackoverflow.com/questions/4720343/loading-basic-html-in-node-js

As you can see this is going to get a bit unwieldy. In the next Tutorial lets look into an easier way to Template our project with Express and Pug.

Related posts

2 Thoughts to “Node JS Tutorial | HTTP Server Basic HTML Templates”

  1. hi

    Spot on with this write-up, I honestly believe that this web site needs a great deal more attention. I’ll probably be back again to see more, thanks for the info!|

  2. That’s a great point

Comments are closed.