在 Rhino 中加载当前文件的相对路径上的文件
我正在Rhino 中编写一个JavaScript 程序,它需要加载其他JavaScript 文件。但是,内置 load()
函数相对于当前目录加载文件,我需要相对于脚本位置加载它们(以便可以从任何目录调用该程序)。
在其他语言中,我会使用类似 dirname(__FILE__) + "/path/file"
的东西,但似乎 Rhino 没有 __FILE__
或类似的东西。我尝试从抛出的异常中提取当前文件,但它是空的,即以下代码打印“true”:
try {
throw new Error();
} catch (e) {
print(e.fileName === "");
}
我尝试查看解释器源代码并使用 Java-JavaScript 桥,但我没有找到任何内容很有帮助(我可能会看更多)。
有人知道如何在相对路径上加载文件吗?
I am writing a JavaScript program in Rhino which needs to load other JavaScript files. However the built-in load()
function loads files relatively to the current directory and I need to load them relatively to the location of the script (so that the program can be called form any directory).
In other languages I would use something like dirname(__FILE__) + "/path/file"
, but it seems that Rhino does not have __FILE__
or anything similar. I have tried to extract the current file from a thrown exception, but it is empty, i.e. the following code prints "true":
try {
throw new Error();
} catch (e) {
print(e.fileName === "");
}
I tried to look at the interpreter sources and use the Java-JavaScript bridge, but I didn't find anything helpful yet (I'll probably look more).
Does anybody have a tip how to make loading files on relative paths work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让用户运行启动器脚本可能是最简单的方法。如果您使用的是 *nix 或 OS X,您可以将 shell 脚本放入与所有 Javascript 相同的目录中,这会在启动之前将该目录更改为脚本的目录:
如果您的脚本需要在用户的当前目录中运行,您可以让包装器在命令行上传递其位置:
然后在 loader.js 中,使用 Rhino 的内置参数变量来访问“$DIR”:
Rhino 函数已记录在案 此处。
Windows 上也可能有类似的情况;我对 CMD.EXE 批处理文件了解不多。
It's probably easiest to get users to run a launcher script. If you're on a *nix or OS X, you could put a shell script into the same directory as all your Javascript, which changes the directory to your script's dir before launching:
If your script needs to run in the user's current directory, you could instead have the wrapper pass its location in on the command line:
Then in loader.js, use Rhino's builtin arguments variable to access "$DIR":
The Rhino functions are documented here.
Something similar may be possible on Windows; I don't know much about CMD.EXE batch files.