Why is Java Nashorn __DIR__, __LINE__ and __FILE__ zero?

I'm trying to get __DIR__, __LINE__and __FILE__ Nashorn globals in a JavaScript file, which is compiled and evaluated Java Nashorn Engine (JDK 8).

However, they all return NULL ...

Are they associated with a specific Nashorn configuration or? The documentation says nothing about any additional configuration to make them work.

+4
source share
1 answer

This is because you probably loaded the script as a string. Most examples:

engine.eval(new FileReader("scripts/hello.js"));

, script, FileReader. engine.eval("print('hello')"), , .

script , jjs, .

Java, : js:

ScriptContext ctx = engine.getContext();
ctx.getBindings(ScriptContext.GLOBAL_SCOPE).put("thisFile", script);

engine.eval(new FileReader(script), defCtx);

js:

print("I am " + thisFile);

:

I am resources/test.js

. , jdk.nashorn.tools.Shell jdk.nashorn.internal.runtime.Context, .

+1

Source: https://habr.com/ru/post/1547694/


All Articles