获取 Rhino 中脚本的路径
Getting the path of a script in Rhino
我正在尝试获取在 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();
}
相关文章:
- 如何在gull注入的脚本路径中删除路径前缀
- 是否可以不在grunt中提及所有的脚本文件路径
- 在JSP中包含java脚本路径
- dist中的GruntJS配置样式和脚本路径
- Java 脚本文件路径未由 SharePoint 标识
- 如何使用 Javascript 获取当前正在运行的脚本的路径
- HTML5 样板和循环渲染路径/引用脚本和样式
- 鲍尔脚本路径引用
- 节点.js相对需要执行脚本的路径
- 动态路径变量播放音频.mp3文件 如何?D3 JavaScript 咖啡脚本
- 如何避免在 js/ajax 脚本中对应用程序上下文路径进行硬编码
- 使用相对路径时无法加载chrome扩展内容脚本
- Illustrator-在文本路径脚本中批量插入文件名会导致Illustrator崩溃
- 外部js脚本中图像的相对路径
- 如何从他自己的js文件中找到脚本路径
- 将文件路径传递给php脚本
- Windows脚本主机查找/运行程序的变量路径使用正则表达式
- 需要前缀脚本文件的路径映射
- 为什么在获取脚本路径时使用自执行匿名函数?
- 如何在构建脚本中添加CDN url以要求路径