How to build a simple webpage in Node.js

So you’ve got Node.js installed, and tested that’s it’s working? Great! Let’s see it in action and dive straight into building a one page website.

For these early tests it’s fine to just use a simple text editor, I’ve been using Gedit on Ubuntu. Just type gedit into terminal to get it started.

Create your file

Create a new text document and save it as app.js.  Enter in the text below and then we’ll take a look at what’s going on.

var http = require('http');  
http.createServer(function(req, res) {  
  res.writeHead(200, {
    'Content-Type': 'text/html'
  });
  res.write('<!doctype html>\n<html lang="en">\n' + 
    '\n<meta charset="utf-8">\n<title>Test web page on node.js</title>\n' + 
    '<style type="text/css">* {font-family:arial, sans-serif;}</style>\n' + 
    '\n\n<h1>Euro 2012 teams</h1>\n' + 
    '<div id="content"><p>The teams in Group D for Euro 2012 are:</p><ul><li>England</li><li>France</li><li>Sweden</li><li>Ukraine</li></ul></div>' + 
    '\n\n');
  res.end();
}).listen(8888, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8888');

Ok great, so what are we looking at here?

Creating the webserver

The first thing to remember – and a big change to get used to if you’re coming over from a Microsoft IIS stack, or an Apache based stack – is that with Node.js there is no webserver until you create it. And that’s what our first two lines are doing.

Calling the HTTP module

Starting at the top, the very first thing we do is load in the pre-prepared HTTP module that ships as part of node. You’ll see this type of syntax a lot, as Node.js programming uses a lot of modules. As a best practice it’s a good idea to set the variable name to match the module name.

var http = require('http');  

Create the server

Stripping out the callback function to make it a little more clear, we can look at the createServer method of HTTP like this:

http.createServer(function(req, res){ }).listen(8888, '127.0.0.1');  

What we are doing here is creating a HTTP server to listen to requests (req) made to port 8888 on the IP address 127.0.0.1, and also send response objects (res)  back to the same IP and port.  The IP address 127.0.0.1  is common across many OS’s as the ‘localhost’ server.

We also output a message to the console to show that we’ve reached the end of the script and that the server is running:

console.log('Server running at http://127.0.0.1:8888');  

But what about the middle bit?!

Okay, so in a nutshell what we’re doing here is responding to any request in exactly the same way. Let’s break that response down.

res.writeHead()

The first part of the response object is another item that you’re probably not used to really thinking about if you’re coming from a traditional stack where the web-server does all this for you. We need to send the HTTP headers. Here we’re  just sending the HTTP status code and content type. So to say that the request was successful, and that we’re sending back HTML content we type:

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

res.write()

Next we want to send some content back to the response object. Here we’re doing it all as one long string:

res.write('<!doctype html>\n<html lang="en">\n' +  
  '\n<meta charset="utf-8">\n<title>Test web page on node.js</title>\n' + 
  '<style type="text/css">* {font-family:arial, sans-serif;}</style>\n' + 
  '\n\n<h1>Euro 2012 teams</h1>\n' + 
  '<div id="content"><p>The teams in Group D for Euro 2012 are:</p><ul><li>England</li><li>France</li><li>Sweden</li><li>Ukraine</li></ul></div>' + 
  '\n\n');

res.end()

To tell the server that we’ve reached the end of the response object we type:

res.end()  

Run your node.js site!

Starting your node.js server is nice is simple. In terminal cd into the directory that you saved your app.js file and type:

node app.js  

All being well you’ll see your console message output to the terminal:
Node.js server running in terminal

Open your node.js site in a browser

Go to your browser and navigate to http://127.0.0.1:8888. Cross your fingers, blink twice and you should see this:
Node.js website running locally

Hurrah and huzzah! You’ve got a webpage running in Node.js :-)

Next time we’ll take a look at how to build this in a more scalable way, creating a basic MVC framework in Node.js!

Get the source code

The source code for this and my other tutorials on Node.js is available on GitHub here: https://github.com/simonholmes/knowing-node/