获取 Rhino 中脚本的路径

Getting the path of a script in Rhino

本文关键字:路径 脚本 Rhino 获取      更新时间:2023-09-26

我正在尝试获取在 Rhino 中执行的脚本的路径。我宁愿不必将目录作为第一个参数传递。我什至没有关于如何获得它的线索。我目前正在通过以下方式致电犀牛

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

并希望 myscript.js 识别/path/to 作为它的目录名称,无论我从哪里运行此脚本。StackOverflow上唯一的其他相关问题和建议是将/path/to作为参数传递,但这不是我正在寻找的解决方案。

你想做的事是不可能的。

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

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

/**
 * 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();
}