Simplicity and Performance: JavaScript on the Server

The award for the hottest new server Web development language goes to...JavaScript! JavaScript, language of the browser since the early days, is the hottest language for server-side development. See why JavaScript is the language for developing quick, easy and incredibly powerful server-side applications.
Sample Program Two: Simple File Server

For the next example, let's serve up files from the local filesystem. If the file is available in the document root, let's return it with a 200 response; if it is not, let's return a 404 status code and an error message.

Like last time, you need the http module. Unlike last time, you also need the modules to read from the filesystem, and an ability to process URLs:

var http = require('http'), fs = require('fs'), 
 ↪path = require('path'), url = require('url');

Create the server and its handler, and listen on port 8080 (just to annoy Tomcat) in the same way as last time:

http.createServer( function(request, response) {
   // handling code
}).listen(8080);

The difference is in the handling code. Now, when you get a request, you want to see whether it exists in the filesystem, and if so, return it:

http.createServer( function(request, response) {
   // __dirname is a special variable set by node
   var file = __dirname+path;
   // check if the requested path exists
   path.exists(file, function(exists) {
     if (exists) {
     } else {
     });
   });
}).listen(8080);

You use the path module to check whether the file is available, but you do it asynchronously. Normally, file access is very slow, and everything in the thread or process will block. With Node's event-driven model, nothing blocks; rather, the system continues to move and calls the function(exists) callback when it has an answer if the file exists.

If the file does exist, you need to read it using the “file” module and send it back. If it doesn't, you send back a 404 error. First, let's look at the simple file-not-found case:

if (exists) {
   // do some handling
} else {
   response.writeHead(404, {"Content-Type": "text/plain"}); 
   response.write("404 Not Found\n");  
   response.end();  
}

Now, let's look at reading the file and sending it back when it does exist. Once again, read the file asynchronously:

if (exists) {
   // read the file asynchronously
   fs.readFile(file,"binary",function(err,file) {
      if (err) {
         // we got some kind of error, report it
         response.writeHead(500,{"Content-Type":"text/plain"});
         response.write(err+"\n");
         response.end();
      } else {
         response.writeHead(200,{"Content-Type":"text/html"});
         response.write(file,"binary");
         response.end();
      }
   });
}

Tying it all together and cleaning it up a bit, you get a nice tidy, asynchronous, event-driven Web file server:

var http = require('http'), fs = require('fs'), 
 ↪path = require('path'), url = require('url');
http.createServer( function(request, response) {
   var file = __dirname+url.parse('url').pathname;
   // check if the requested path exists
   path.exists(file, function(exists) {
      if (exists) {
         fs.readFile(file,"binary",function(err,file) {
            if (err) {
               response.writeHead(500,{"Content-Type":"text/plain"});
               response.write(err+"\n");
               response.end();
            } else {
               response.writeHead(200,{"Content-Type":"text/html"});
               response.write(file,"binary");
               response.end();
            }
         });
      } else {
         response.writeHead(404, {"Content-Type": "text/plain"});  
         response.write("404 Not Found\n");  
         response.end();  
      }
   });
}).listen(8080);

A static Web file server, which will outperform most such servers on the market, in just 23 lines of code—it's a work of Art.

Summary

Node.JS is an incredibly powerful, simple and elegant engine to run event-driven server-side JavaScript, and it has been a catalyst for an enormous amount of fermentation in the server-side world during the past year and a half.

Avi Deitcher is an operations and technology consultant based in New York and Israel who has been involved in technology since the days of the Z80 and Apple II. He has a BS in Electrical Engineering from Columbia University and an MBA from Duke University. He can be reached at avi@atomicinc.com.

______________________

Webcast
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers

Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.

Learn More

Sponsored by AMD

White Paper
Red Hat White Paper: Using an Open Source Framework to Catch the Bad Guy

Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6

Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.

Learn more about catching the bad guy in this free white paper.

Learn More

Sponsored by DLT Solutions