17 July, 2011

Making command line JavaScript ready for node.js AND rhino

I have several command line scripts for doing repetitive chores. As seen in a previous post, I used rhino to run the scripts. But since node.js has been arising, I guess many developer will use that one as JavaScript interpreter. It also starts a bit faster that rhino.

The problem is that the two are not very compatible since the hooks to the operating system are named differently. This will lead to errors when one engine executes scripts designed for the other.

Here is a workaround that can make basic scripts, not using too many internals, compatible with each other. It works well for my string conversion scripts.
var args = arguments;

//initalize for node.js/rhino compatibility
if(typeof print === 'undefined') print = console.log;
if(typeof console === 'undefined') console = { log: print };
if(typeof process !== 'undefined') args = process.argv.splice(2); 
This script does two things:
  1. It maps the command line arguments to args. Node.js stores them in process.argv and rhino in the default arguments array.
  2. It will merge the basic logging functionality of rhino and node.js, mapping node.js' console.log to rhino's print function and vice versa.
That's it! I hope you can make use of this little hint.