我正在尝试获取在Rhino中执行的脚本的路径。我宁愿不必将目录作为第一个参数传递。我甚至没有领导如何获得它。我正在通过
打电话给Rhinojava -jar /some/path/to/js.jar -modules org.mozilla.javascript.commonjs.module /path/to/myscript.js
并希望myscript.js识别/ path / to为它的dirname,无论我从哪里运行此脚本。唯一的其他相关问题& StackOverflow上的建议是将/ path / to作为参数传递,但这不是我要寻找的解决方案。
答案 0 :(得分:2)
不可能做你想做的事。
检测JavaScript解释器运行的脚本源的能力不是ECMAScript语言规范或Rhino shell extensions的一部分。
但是,您可以编写一个包装器可执行程序,该程序将脚本路径作为其参数并在Rhino中执行脚本(例如,通过调用相应的主类)并将脚本位置作为环境变量(或类似)提供。
答案 1 :(得分: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();
}