When you’re brainstorming some ideas for a program or learning a new language its great to have an interactive console to play with. It lets you start typing out code, inspect the return values, and experiment or debug in a really helpful way. You get immediate feedback on what each line of your code is doing. That’s why irb for ruby or script/console for your rails app are such great and useful tools. Once you get used to being able to dive into your application environment and fiddle around you wonder how you ever did without it.
There’s a cross-platform Javascript shell, which is super easy to get up and running. It uses Rhino which is an open-source implementation of JavaScript written entirely in Java.
I’ll show you how to install it on OS X in under 5 minutes.
Most of this should work on Linux (and maybe Windows) too with some minor tweaks.
First thing you’ll need to do is download Rhino.
$ wget ftp://ftp.mozilla.org/pub/mozilla.org/js/rhino1_7R2.zip
$ unzip rhino1_7R2.zip
Then copy the js.jar file where java can find it. On OS X
$ cd rhino1_7R2
$ cp ./js.jar /Library/Java/Extensions/
On Linux you’ll want to put the jar file in JAVAHOME/jre/lib/ext
for example: /usr/local/java/jre/lib/ext.
On Windows it’ll be someplace like C:\j2sdk1.4.1_03\jre\lib\ext
$ java org.mozilla.javascript.tools.shell.Main
This is a little unwieldy so I put this following alias in my ~/.bashrc which lets me just type js to get into the console.
alias js='java org.mozilla.javascript.tools.shell.Main'
That was easy, but I quickly realized, this console really sucks. I can’t backspace or use the arrow keys or ctl-A, ctl-E to move around. Well not to worry. JLine to rescue.
As its website states:
JLine is a Java library for handling console input. It is similar in functionality to BSD editline and GNU readline. People familiar with the readline/editline capabilities for modern shells (such as bash and tcsh) will find most of the command editing features of JLine to be familiar.
Just download the library:
$ wget http://superb-west.dl.sourceforge.net/sourceforge/jline/jline-0.9.94.zip
Unzip it and copy the jline-0.9.94.jar file to same place you put js.jar (/Library/Java/Extensions/ on OS X.)
Congrats. Now you’ve got a javascript shell that doesn’t suck.