Servers

Take your JavaScript skills to the server with node.js

The node.js framework makes JavaScript programming easier by embracing real-time application development with an event-driven, non-blocking I/O approach.

The many JavaScript libraries and frameworks that are now available have added legitimacy to the programming language, and node.js (Node for short) brings it full circle with a simple yet robust server environment. That's right - you can take your JavaScript programming skills to the server.

It is the server

Node isn't the first time JavaScript has been brought to the server (anybody remember LiveScript?), but it does seem to be the most successful effort. Node has been around for three years, but it gained momentum recently when Microsoft embraced it on its Azure cloud platform. A big difference between other environments that may run on Web servers like IIS or Apache is Node is the Web server; that is, a Node application is built as the Web server - it is coded to respond to certain requests or events. Node is built on Google Chrome's V8 JavaScript engine; it embraces real-time application development with an event-driven, non-blocking I/O approach.

Event-driven programming

Web developers are fully aware of event-driven programming in the browser via JavaScript and DOM events - frameworks like postal.js embrace it. Events are a core principle in Node. Node programs run and wait for things (events) to happen and respond. There are no concerns about threading -- a Node application sits and waits for a request. As requests are received, they are processed. Node is more of a small event model as it seems to be set up to respond to lots of requests. Node applications/servers are continuous loops that process incoming requests. The requests are processed, callback is set up, and it moves on to the next request. It never sits there processing a request (like waiting for a process to complete) and blocking incoming traffic - it is in continuous motion going round and round.

Up and running

Node is available for all of the popular operating systems (Windows, Linux, Mac OS X), and you can download the source to build it on other platforms. Its website includes installers for Windows and Mac OS X systems; it is also available on GitHub. Installation on my Windows 7 test machine results in a base directory with the Node runtime (node.exe).

  • node.exe: The Node runtime that allows you to execute programs (node.exe file.js) and execute code interactively (node.exe without a file passed to it).
  • npm.cmd: The Node package manager that is used to install/delete/manage modules.
  • node_modules: A subdirectory containing all installed Node modules and other basic Node resources like the license file.

Once installed, you can launch Node interactively at the command line by typing node.exe. You can type the following lines to see it in action:

var test = 1;
if (test == 1) { console.log("true") }  else { console.log(‘false'); }

As you type these at the command line, the code is executed with true displayed. This interactive way to use Node is called Read-Eval-Print-Loop, though you'll see it called REPL in documentation and other articles. It is not a way to use Node in production, but it does provide a mechanism for testing/debugging or just playing with code.

Node applications are built as Web servers; the following sample provides a quick look at this in action. The code creates an instance of an HTTP/Web server that listens for requests on port 8135 on the localhost (127.0.0.1).

The first line uses the require keyword to import a module to be used in the code. Modules are a core component of Node - the installation includes a number of modules, but there are plenty more modules available from third parties. This modularity follows the CommonJS standard for modularization and distribution.

The second line uses the createServer method to create a new server instance. The function inside this method call defines how requests to this server instance are handled. The function has two parameters that define a Web request: the first parameter is the request and the second is the response. In this example, nothing is done with the actual request - the only thing happening is sending basic output via the response. The listen method is called on the server to define where it is running/listening for requests. The final line in the code is a basic statement that sends output to the console to show the server is running.

var webServer = require('http');

webServer.createServer(function (req, res) {

res.writeHead(200, {'Content-Type': 'text/plain'});

res.end('Visit TechRepublic.com Every Day!\n');

}).listen(8135, "127.0.0.1");

console.log('Server running at http://127.0.0.1:8135/');

You can test this code in your local browser where you will see the basic text displayed.

A simple Google search will turn up a ton of Node examples. That's how I found the following example (to which I made minor changes) that sets up a file server with a few lines of code:

var util = require("util");
var http = require("http");

var  url = require("url"),

path = require("path"),

fileSystem = require("fs");

http.createServer(function(req, resp) {

var loc = url.parse(req.url).pathname;

var filename = path.join(process.cwd(), loc);

path.exists(filename, function(exists) {

if (!exists) {

resp.writeHead(404, {"Content-Type": "text/plain"});

resp.end("404 Not Found\n");

return;

}

fileSystem.readFile(filename, "binary", function(error, file) {

if(error) {

resp.writeHead(500, {"Content-Type": "text/plain"});

resp.end(error + "\n");

return;

}

resp.writeHead(200);

resp.end(file, "binary");

});

});

}).listen(8081);

console.log("Your File Server is running at http://localhost:8081/");

Basically, the code creates a server that listens on port 8081. It takes a file name as a parameter passed to the server via the querystring. If this file is found, it is displayed in the browser; otherwise, an error is displayed. The first few lines of code import modules via the require keyword. The url module is used to parse the file name from the application's URL, and the path module is used to work with the local file system. The fs module allows us to interact with the local file system, thus displaying the contents of the file in the browser.

Do you always use the hammer?

Every new technology has zealots who use it for everything, but Node is not a swiss army knife. It is good for certain applications like processing a lot of requests with small amounts of data. One area where I can see it being useful is social media applications where little bits of data are processed quickly (think of Twitter). On the other hand, I don't see a traditional data intensive, full-featured Web application being built with Node.

Node is still a baby and will continue to grow, which is why it's a good time to jump on board. As I mentioned, you can find great example code online, and O'Reilly's Node: Up and Running is an excellent resource when you're getting started.

Keep your engineering skills up to date by signing up for TechRepublic's free Software Engineer newsletter, delivered each Tuesday.

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

0 comments

Editor's Picks