开发者

Getting the path of a script in Rhino

I'm trying to get the path to a script executing in Rhino. I wou开发者_运维技巧ld prefer to not have to pass in the directory as the first argument. I don't even have a lead on how to get it. I'm currently calling Rhino via

java -jar /some/path/to/js.jar -modules org.mozilla.javascript.commonjs.module /path/to/myscript.js

and would like myscript.js to recognize /path/to as it's dirname, regardless of where I run this script from. The only other related question & suggestion here on StackOverflow is to pass /path/to as an argument, but that is not the solution I am looking for.


It's not possible to do what you want.

The ability to detect the source of the script being run by a JavaScript interpreter is not a part of the ECMAScript language specification or the Rhino shell extensions.

However, you could write a wrapper executable program which takes a script path as its argument and executes the script in Rhino (e.g. by calling the appropriate main class) and also providing the script location as an environment variable (or similar).


/**
 * Gets the name of the running JavaScript file.
 *
 * REQUIREMENTS:
 * 1. On the Java command line, for the argument that specifies the script's
 *    name, there can be no spaces in it. There can be spaces in other 
 *    arguments, but not the one that specifies the path to the JavaScript 
 *    file. Quotes around the JavaScript file name are irrelevant. This is
 *    a consequence of how the arguments appear in the sun.java.command
 *    system property.
 * 2. The following system property is available: sun.java.command
 *
 * @return {String} The name of the currently running script as it appeared 
 *                  on the command line.
 */
function getScriptName() {
    var scriptName = null;

    // Put all the script arguments into a string like they are in 
    // environment["sun.java.command"].
    var scriptArgs = "";
    for (var i = 0; i < this.arguments.length; i++) {
        scriptArgs = scriptArgs + " " + this.arguments[i];
    }

    // Find the script name inside the Java command line.
    var pattern = " (\\S+)" + scriptArgs + "$";
    var scriptNameRegex = new RegExp(pattern);
    var matches = scriptNameRegex.exec(environment["sun.java.command"]);
    if (matches != null) {
        scriptName = matches[1];
    }
    return scriptName;
}

/**
 * Gets a java.io.File object representing the currently running script. Refer
 * to the REQUIREMENTS for getScriptName().
 *
 * @return {java.io.File} The currently running script file
 */
function getScriptFile() {
    return new java.io.File(getScriptName());
}

/**
 * Gets the absolute path name of the running JavaScript file. Refer to
 * REQUIREMENTS in getScriptName().
 *
 * @return {String} The full path name of the currently running script
 */
function getScriptAbsolutePath() {
    return getScriptFile().getAbsolutePath();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜