Saturday, 29 June 2013

Creating a simple HTTP server (in-depth node.js series)

Creating a HTTP server in node.js is almost trivial. Node makes extensive use of modules for almost all functionality. In this tutorial we will be using a module called http. This module will help us create a HTTP server, that can serve web requests made from the users' browsers.

We will now be creating a server, that will serve a hello world page. So, fire up your favorite text editor (which is likely to be vi or gedit if you are on Ubuntu), create a file named, say, test.js, and type in the following code.
var http = require('http');

// This function will be the one which will be serving
// the webpages. It accepts a request and a response object.
// For now, we will be using only the response object.
function serve(request, response) {
        {'Content-Type': 'text/html'}

// We now create the actual server, and pass the function
// that tells the server what to serve. This server will
// listen at the port 12430. You can pick any other number,
// but make sure there is no other server using that port.
var server = http.createServer(serve);
That is all. Your server is now ready. To start it, go to the command line, and type in the following,
node test.js
You will not get the command prompt again. This means, your server is now active and ready to serve requests. Just open any web-browser, and visit, You should see the string Hello.

There, we now have a working HTTP server with node. To stop this server, just go back to that terminal where you started it, and press Control+C.

Hope you found this tutorial useful. Lots more to come in this series, so your comments and feedback will be invaluable to me.

No comments:

Post a Comment