views:

320

answers:

1

I am writing a JavaScript program in Rhino which needs to load other JavaScript files. However the built-in load() function loads files relatively to the current directory and I need to load them relatively to the location of the script (so that the program can be called form any directory).

In other languages I would use something like dirname(__FILE__) + "/path/file", but it seems that Rhino does not have __FILE__ or anything similar. I have tried to extract the current file from a thrown exception, but it is empty, i.e. the following code prints "true":

try {
  throw new Error();
} catch (e) {
  print(e.fileName === "");
}

I tried to look at the interpreter sources and use the Java-JavaScript bridge, but I didn't find anything helpful yet (I'll probably look more).

Does anybody have a tip how to make loading files on relative paths work?

A: 

It's probably easiest to get users to run a launcher script. If you're on a *nix or OS X, you could put a shell script into the same directory as all your Javascript, which changes the directory to your script's dir before launching:

#!/bin/sh
cd `dirname "$0"`
java -jar js.jar your_script.js

If your script needs to run in the user's current directory, you could instead have the wrapper pass its location in on the command line:

#!/bin/sh
DIR=`basename "$0"`
java -jar "$DIR/js.jar" "$DIR/loader.js" "$DIR"

Then in loader.js, use Rhino's builtin arguments variable to access "$DIR":

load(arguments[0] + "/another_js_file.js");

The Rhino functions are documented here.

Something similar may be possible on Windows; I don't know much about CMD.EXE batch files.

Andrew
I thought about a wrapper script, but only as a last resort. Since there does not seem to be any other way, I ended up using it. Thanks for your answer.
David Majda