Prash's Blog

Simple Nodejs Application April 17, 2012

Filed under: Nodejs — prazjain @ 2:33 pm
Tags: ,

A simple example of how to write a nodejs application. (This is from the nodejs for beginner ebook).

What is NodeJs? – Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications.

Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for
data-intensive real-time applications that run across distributed devices.

For this example we can have all functions in same file / module but for sake of clarity we will create functions in different modules.
The js files mentioned below will need to be in the same directory. (You can keep it in different directory given that you also update the file path reference accordingly).

Create Index.js :

// create instance of server module that we have defined in another js file
 var server = require("./server");
 // create instance of router module that we have defined in another js file
 var router = require("./router");
 // create instance of requestHandler module that we have defined in another js file
 var requestHandlers = require("./requestHandler");

// here we use an array to create a mapping of url pattern and the functions that will handle processing for those requests.
var handle = {}
// start function will need to be exported by requestHandler module
handle["/"] = requestHandlers.start;
// start function will need to be exported by requestHandler module
handle["/start"] = requestHandlers.start;
// upload function will need to be exported by requestHandler module
handle["/upload"] = requestHandlers.upload;

// the server module created above will need to export a start function with two arguments, and we call that for further processing

Here we are creating instance of server, router, requestHandler module that are defined by us in separate js files.
We will also associate url mapping with different modules so we can separate processing of different request in different module and have clearner js files :).

Now we define server.js file like this :

// create instance of http module of nodejs
var http = require("http");
// create instance of url module of nodejs
var url = require("url");

// define a function start
function start(route,handle)
 // we will use this function to process incoming requests from http server
 function onRequest(request, response)
 // extract the pathname from the url requested by user
 var pathname = url.parse(request.url).pathname;
 console.log("Request for " + pathname + " received.");

// invoke route with the url-handler pair mappings, the pathname requested by user, and response object where output can be sent for the user.
// route function is responsible to routing the request based on pathname to the appropriate handler
 route(handle,pathname, response);

// we invoke createServer function exposed by http module and listen on port 9999
 // here onRequest function is called when we receive a request.

console.log("Server has started.");
 // we export the start function above as start
 exports.start = start;

Here we create instances of nodejs modules : http and url.
http module provides us with function to create an http server listening at a particular port.
url module provides us with functions to perform processing on urls (ofcourse), like getting path, querystring etc.

Now lets define router.js file :

// we define a route function that takes url-handler pair mappings, pathname from user url request, and response object for user

function route(handle,pathname,response)
 console.log("About to route a request for " + pathname);
 // check if we have a handler for this pathname pattern
 if (typeof handle[pathname]==='function')
 // invoke the handler
 // else we send a 404 response
 console.log("No request handler found for " + pathname);
 response.write("404 Not found");
 // we export the route function above as route
 exports.route = route;

Finally the requestHandler.js contains the logic to perform appropriate actions for a requested pathname :

// create instance of child process module to use the exec function asynchronously
 var exec = require("child_process").exec;

function start(response)
 console.log("Request handler 'start' was called.");

// we invoke dir system command, you can replace it with "ls -l" if you are using linux
 // only when the command has finished the callback function in second argument is called with the three parameters having values from corresponding streams

// we write the output from stdout back to the user and close the response object
 exec("dir",function(error, stdout,stderr)

// a placeholder function that just write a Hello message back to user
 function upload(response)
 console.log("Request handler 'upload' was called.");
 response.write("Hello Upload");

// exports start function
 exports.start = start;
 // exports upload function
 exports.upload = upload

Once you have done all of this you can start your application like this :

node index.js

Happy Nodejs’ing!


One Response to “Simple Nodejs Application”

  1. […] this post we will build up on the simple nodejs application we wrote earlier and add the functionality to allow user to upload a pdf file and show the pdf back […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s