2011-05-18 86 views
2

我试图获取在Rhino中执行的脚本的路径。我宁愿不必传入目录作为第一个参数。我甚至没有领导如何得到它。目前,我正在通过在Rhino中获取脚本的路径

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

调用犀牛,想myscript.js识别/路径/为它的目录名,无论在哪里,我运行此脚本。唯一的其他相关问题& StackOverflow的建议是传递/ path/to作为参数,但这不是我正在寻找的解决方案。

回答

2

这是不可能做你想做的。

检测由JavaScript解释器运行的脚本源的能力不是ECMAScript语言规范或Rhino shell extensions的一部分。

但是,您可以编写一个包装程序可执行程序,它将脚本路径作为其参数并在Rhino中执行脚本(例如,通过调用相应的主类)并提供脚本位置作为环境变量(或类似) 。

+0

谢谢,我很害怕这个。我从小道消息中得知,犀牛开发者认为包括这样的东西毫无意义,并且它不会被释放。不幸的是,犀牛需要它,因为它们的“require”实现不完整。 Node.js确实提供了它,所以我认为Rhino也可以。您的建议正是现在如何实施的。 – 2011-05-19 02:52:44

0
/** 
* 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(); 
} 
相关问题