Node by example

Node by example: 2. Hello World

2. Hello World

The complete source code can be downloaded here:

It's the same old same old, but here goes:
The Node.JS "Hello World" example is a http server that serves a "Hello World" output 2 seconds after a client connects to the server.

var sys = require('sys'),
http = require('http');

http.createServer(function(req, res) {
  setTimeout(function() {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('Hello World');
  }, 2000);
sys.puts('Server running at');

Run the code via:

node hello_world.js

Now open your browser and access or the IP/URL of the remote server, in case you are running the code not on your local machine.

The code in detail:
At first we include 2 of Node.JS built-in modules, "sys" and "http", by using the

var some_var = require("built-in_module_name");


var sys = require('sys'),
  http = require('http');

The "sys" module provides features to output data to the command line, for example.
The "http" module provides the needed HTTP server feature for this code sample.
You can include your own modules, more on that in the next part.

Next we create the HTTP server and make it listen to port 8000:

http.createServer(function(request, response) {

The request object contains details about the request, such as the request method (GET, POST, DELETE, ...), the request URL, headers, ...
and the response object is used to send a response to the request, such as the "Hello World" output.

As mentioned before, the server waits 2 seconds before sending any output, which is what the setTimeout() function is used for.setTimeout(function() { ... }, 2000);After the 2 seconds are over the code in the provided callback is executed:

response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('Hello World');
First we send a header to the client with the status code 200 (OK) and the content-type specified as text/plain.
After sending the header you can send data to the client using the response.write() function.
Only thing left is to close the response, which signals to the server that all of the response headers and body have been sent. This method *must* be called on each response!

The last line outputs "Server running at" to the command line, once you start the script:
sys.puts('Server running at');
That's it. With just a few lines of code you have a simple HTTP server up & running that serves "Hello World" to any client requests.