Hello World in Node.js

by Michael Clark
November 18, 2011 10:59 AM

Node.js has been one of the latest buzz words in the development community, but what exactly is it? Node’s community wiki calls it a server-side JavaScript environment that uses an asynchronous event-driven model. I’ve been interested in learning more about JavaScript and the server-side statement was enough to pique my interest to learn more.

Since this is going to be an introduction to Node piece, we’ll go through the traditional “Hello World” piece. Here’s a snippet directly from the Node website that creates a web server which responds to every request with “Hello World” –

var http = require('http')
http.createServer(function (req, res) {
   res.writeHead(200, {'Content-Type': 'text/plain'});
   res.end('Hello World\n');
}).listen(1337, "");
console.log('Server running at');

Let's go line by line and explain what's going on with these 6 lines of code.

The first line, according to the Node API, is required in order to use the HTTP server and client. It essentially includes the http library similar to how you might include the System.IO namespace in C#.

The createServer function is from the http library and takes a callback function while returning a new server object. In this case, the callback function is listen. The listen function takes two parameters, but only one is required. In our case we provide both - the first one is required and is the port to listen on and the second is the hostname URL. 

The meat of the createServer function has two calls - writeHead and end. The first call, writeHead, has a couple of arguments we can pass in. The first argument is the status code of the request (200 or OK in this snippet). The second is an object containing all the response headers we'd like to set (we're just setting the Content-Type header here). The end call allows us to pass in the string we'd like to print out (Hello World) and signals to the server that the response is ready.

The last line prints out a simple message to the console that lets us know the server is running and what it port it's listening on.

Pretty straightforward, isn't it? If you're interested in seeing something in action, check out the Node chat room. Both the client-side and server-side were written in Javascript.

My last post was on crawling FHU.edu and what got me interested in Node was an article on scraping web pages with Node.js and jQuery. I may try that out sometime when I get the chance - especially since Node now runs in Windows natively as of November 11.

Add comment

  • Comment
  • Preview