Javascript Shell in Your Terminal

by jasonyeo

I’m currently working on the Sage Notebook and I’ve been writing code in javascript. To test snippets of js code, I usually open up either firebug or the dev console on Chrome to test it. Which is pretty annoying. I have to wait for the browser to load, then I’ve to wait for firebug to load, then I have to click on the console prompt in firebug. So, I’ve decided to look for a quicker solution to my problem. I’ve previously seen a talk that a web developer gave (it’s really funny, you should watch it!) and he gave live demos of javascript running on his command line. Kinda like a javascript repl. So I’ve decided to look for it and I found rhino.

Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users. It is embedded in J2SE 6 as the default Java scripting engine.

The best thing about rhino is that it has a javascript shell. (IMO, that’s the best thing about it. It comes with other cool things like a debugger by the way.)

Setting Up Rhino (On the OSX)

First, download Rhino. Extract it. Then, create the ~/Library/java/Extensions directory if it’s not created yet. Lastly, copy js.jar from the rhino folder to ~/Library/java/Extensions. Or you can copy and paste the following commands to your Terminal.

mkdir -p ~/Library/java/Extensions
cp ~/Downloads/rhino1_7R3/js.jar ~/Library/java/Extensions

To test it, execute this in the Terminal:

java org.mozilla.javascript.tools.shell.Main

You should see this in your Terminal:

Rhino 1.7 release 3 2011 05 09
js>

And..you’re done. Oh a quick tip, instead of typing that long command to your terminal, you can alias it. You can do so by putting this in your ~/.bash_profile:

alias js="java org.mozilla.javascript.tools.shell.Main"

Enjoy!

Note: If you want to have readline capabilities like line editing, history, etc, you might want to put this in the ~/.bash_profile instead:

alias js="rlwrap java org.mozilla.javascript.tools.shell.Main"

Advertisements