David King

full stack developer

All Blog Articles

Prev « How to install node.js on Linux Next » New Years Resolutions


Hello world... of node.js

01 Jan 2012

Previously: How to install node.js on Linux

Today we learn how to create a simple webserver with node, it'll take you about 3 minutes :-)

Create a file called server.node.js and dump this into it:

/**
 * Hello world server
 *   every request to the ip gets the same response
 */

// Require the http library
var http = require('http');
// Create the server
var server = http.createServer(function (request, response) {
	// Every request outputs "hello world"
	response.writeHead(200, {'Content-Type': 'text/plain'});
	response.end('Hello World\n');
	// And also logs 
	console.log('Page requested at ' + new Date() + ', for ' + request.url);
});
// It listens on port 1337 and IP 127.0.0.1
server.listen(1337, "127.0.0.1");
// For the joy
console.log('Server running at http://127.0.0.1:1337/');

Open up the terminal and run:

node server.node.js

Then navigate to the server URL, you can watch the terminal output messages to the following effect:

Server running at http://127.0.0.1:1337/
Page requested at Sun Jan 01 2012 16:23:12 GMT+0000 (GMT) /
Page requested at Sun Jan 01 2012 16:23:12 GMT+0000 (GMT) /favicon.ico

Pretty simple stuff really, and you should be able to quickly see how node.js can become a useful tool to add to your arsenal.

Next up: node.js - a static file server


Prev « How to install node.js on Linux Next » New Years Resolutions