Fresh Blurbs

Command-Line Javascript (CLI) On Mac OS-X

With the increasing popularity of server-side Javascript, you may want to have Javascript everywhere. You can use Javascript outside of a browser, on any platform. There are many choices: you can install Mozilla SpiderMonkey, Google V8 or Mozilla Rhino. If you are like me and use Mac OS-X as your development machine, however, you have hit a jackpot: OS-X Leopard and later come with Javascript CLI pre-installed. The CLI uses JavascriptCore by Apple, the same engine used in the Safari browser, and many other places all over OS-X.

This is how you can enable JSC:

$ sudo ln -s /System/Library/Frameworks/JavaScriptCore.framework/Versions/Current/Resources/jsc /bin/jsc

Once you do that, you can run the jsc interactive shell or write javascript shell executables by putting:

#!/bin/jsc

at the top of a shell script. JSC Wiki lists some extra commands you can use in your CLI scripts.

Alternative JS CLIs

If you install Homebrew, "the missing package-manager for OS X" (generally a great idea for a developer), installing Google v8 or Mozzila Spidermonkey or Rhino becomes trivially easy:

$ brew install v8
$ brew install spidermonkey
$ brew install rhino

For Rhino, you need to make sure you have Java installed on your Mac. If you do that, JS executables will correspondingly be located in:

/usr/local/Cellar/v8/HEAD/bin/v8
/usr/local/Cellar/spidermonkey/1.8.5/bin/js
/usr/local/Cellar/rhino/1.7R3/bin/rhino

Typically, brew will also create convenience symlinks:

/usr/local/bin/v8
/usr/local/bin/js
/usr/local/bin/rhino

For quick shell-script prototyping, Spidermonkey is my favorite because you can put:

#!/usr/local/bin/js

at the top of a shell script, making it executable, and Spidermonkey is much more debuggable than JSC (which swallows error messages).

If you need to load an existing Javascript library, or break your script up into multiple files, all you need to do is write something like the following in your script:

load("included.js");

where "included.js" is some javascript in the same folder as your main script file (and does not contain "#!/usr/local/bin/js")

Pretty neat stuff, overall.

comments powered by Disqus