Simplicity and Performance: JavaScript on the 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.
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.
Resources
Node.JS: nodejs.org
Node.JS Git Repo: github.com/ry/node
CommonJS: www.commonjs.org
Cygwin: www.cygwin.com
Nginx: nginx.org
Douglas Crockford: www.crockford.com
Language Popularity: www.webdirections.org/the-state-of-the-web-2008
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.
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.
Sponsored by AMD
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.
Sponsored by DLT Solutions
Web Development News
Developer Poll
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- New Products
- Linux Systems Administrator
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- Web & UI Developer (JavaScript & j Query)
- Designing Electronics with Linux
- Dynamic DNS—an Object Lesson in Problem Solving
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development








1 hour 11 min ago
11 hours 51 min ago
17 hours 37 min ago
17 hours 55 min ago
19 hours 48 min ago
21 hours 41 min ago
1 day 4 hours ago
1 day 4 hours ago
1 day 6 hours ago
1 day 12 hours ago