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.

______________________

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState