An Un-new Idea: Server-side JavaScript

Thursday, November 19, 2009 - Jerry Sievert

My first few run-ins with JavaScript left me wanting. JavaScript was in its infancy, the platform was fairly immature, and I had my sites set on the server side.

Fast-forward a decade, and I found myself taking a job writing software for big-box retail product finders: the platform was Mozilla XUL, running on embedded Linux systems, the development environment a mix of JavaScript and C++ sprinkled liberally with JSUnit.

Spending that much time writing JavaScript made me completely re-evaluate the language. Who knew? I realized that the potential in JavaScript was simply limited by the imagination of the user. Connecting to hardware was as simple as writing some glue-code, access to the filesystem was easy, anything I wanted to do was possible. But, when I eventually moved on, I never really thought about taking it much further.

A few years later, I got to thinking: at this point, the most ubiquitous language on the internet has to be JavaScript. Why not exploit that connection? Enter server-side JavaScript. Sure, this is far from a new idea -- Netscape's webserver allowed for server-side JavaScript way back in the 90's, but it seems to have been forgotten.

So, I got busy. Once again I reached into my toolbox and grabbed out my handy perl tool; a few lines of code later, I had a simple mod_perl handler for Apache.

 
 SetHandler perl-script
 PerlHandler Handler::Javascript
 
Apache Configuration

The trick is simple: intercept the request for a file in Apache, load the file, find the parts to interpret, and interpret them. Some simple glue code provides input and output and the rest is a mix of HTML and JavaScript.


You can even include other JavaScript:


Get and set parameters:
// create a new Request object
var request = new Request();

// gets the value of passed parameter abc
var abc = request.param('abc');

// set the value of parameter abc to 123
request.param('abc', '123');
Set headers:
request.header('-type', 'application/json');
request.header('-creator', 'super special javascript thingy');

Essentially, the sky is the limit. Extending functionality is fairly simple: the JavaScript module provides some hooks into the interpreter allowing you add any additional functionality needed, from defining document objects to emulating the DOM, to providing direct access to native models, to native socket code. Anything that can be accessed in any other language can effectively be exported to the JavaScript interpreter.

Once again, there are a few prerequisites:

And this is in no way anything more than a pointless exercise.

Code is here