2011-05-18 81 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(); 
} 
相關問題