Javascript from the command line

In Linux and Windows. (Goodbye Cscript!)
Mozilla Rhino

A few years ago I wrote about Windows command line text processing with Javascript using Microsoft's Cscript utility. I was surprised to find no Linux equivalent, and while I'd heard of Mozilla Rhino I had some vague ideas about how using it only meant integrating it into other applications.

After some hunting, I learned that Rhino includes a jar file that makes it easy to run a script from the command line. Once you have it, running a script named myscript.js is as simple as this:

java -jar js.jar myscript.js

If you're really interested in text processing, you can pipe and redirect the output.

After I downloaded Rhino and got this to work I searched my hard disk and found that js.jar was already on my hard disk in several places: with OpenOffice, with Swoop, and with Eclipse (and therefore with TopBraid Composer), so I've had it right under my nose for years. My brother checked his Mac and found that js.jar came with an open source speech recognizer that he had installed.

One neat part was that some fairly complex JavaScript scripts that I had run with Cscript ran with js.jar after one minor change that actually improved the scripts: instead of a print() function for basic text output, Cscript has this WScript.Echo() thing instead (WScript is a more Windows-oriented version of Cscript), so I had put the following function in my command-line JavaScript scripts:

function print(OutString) {

Because js.jar supports a native print() function, the only change necessary to any of my scripts was to comment out the three lines above, and js.jar then happily ran my existing scripts.

If you start up js.jar without providing a script name as an argument, you get a js command line. Enter help() there to see some interesting commands that you can add to your scripts—for example, readUrl(). (Note that these commands are case-sensitive.)

I mostly tested this on a Windows machine, but it all worked fine on a machine running the latest Ubuntu.

The reason I got interested in this recently was that I had just pulled a ton of menu definition JavaScript off a website, with the majority of it being JSON definitions of the website's menu structure. I wanted to store all these definitions in SKOS RDF. Once I added and redefined a few functions in the JavaScript code that I had downloaded, I ran it all and redirected the output to RDF files all pretty easily. I'm definitely going to have some more fun with this.

Please add any comments to this Google+ post.