Building server and client applications using JavaScript

JavaScript has become an essential tool that allows web developers to produce sophisticated web applications that often use AJAX to communicate with the server. JavaScript source code is becoming increasingly more complex and so it has become necessary for web browser developers to increase the performance of their JavaScript virtual machines.

Google Chrome features the v8 JavaScript environment which provides outstanding performance by compiling JavaScript into machine code (as opposed to being processed by a virtual machine). The performance boost is massive. V8 is released under an open-source license (http://code.google.com/p/v8/) which can be compiled and used as a standalone JavaScript processor, or more interestingly integrated into custom applications!

V8 could easily be integrated into an application (or game) to provide an extremely powerful and flexible scripting language. It is possible to map functions and classes between the V8 execution context and a C++ application.

A while back I bumped into a project called nodejs. Initially I wasn’t sure what this project was offering nor how it related to JavaScript. It turns out that nodejs is built on top of the powerful V8 JavaScript engine and provides networking capabilities that can be used to produce server applications extremely easily. I would thoroughly recommend watching the video on the project home page for some excellent tutorials.

Here is a very simple web server written in JavaScript that can be executed using nodejs:

var http = require("http");
var server = http.createServer(function(request, response) {
  response.writeHead(200, { "Content-Type": "text/html" });
  response.write('<h1>Hello World!</h1>');
  response.end();
});
 
// start web server on port 8080 (http://localhost:8080)
server.listen(8080);

This is also an excellent resource: http://www.nodebeginner.org/

One of the things that confused me was that I thought that nodejs could only be used to develop web server applications. But this isn’t true because nodejs can be used to develop client applications that run from the command line. Better still, nodejs can be compiled to work on Mac, Unix and Windows.

There are also a vast selection of modules that can be used alongside nodejs to allow interaction with databases, frameworks for developing powerful web servers easily. Some JavaScript libraries can be used by a web browser and nodejs environment when implementation specific features (like the DOM in a web browser, or process in nodejs) are not needed.

I do not think that nodejs is a replacement for PHP at the moment because the project is still in its infancy. This could, however, be the case in the future once nodejs and various modules have had a little time to mature. It is certainly a fun project to experiment with.