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.

______________________

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix