user1807754
user1807754

Reputation:

Why Java Nashorn __DIR__, __LINE__ and __FILE__ are null?

I am trying to get __DIR__, __LINE__ and __FILE__ Nashorn globals within JavaScript file which is compiled and evaluated by Java Nashorn Engine (JDK 8).

However, all of them return NULL...

Are they related to some specific Nashorn configuration or? It doesn't say anything in the documentation about any additional configuration to get them working.

Upvotes: 5

Views: 1506

Answers (2)

jbsarrodie
jbsarrodie

Reputation: 56

I know this is an old question, but as I came up with a simple solution I wanted to share it to help people that face the same issue.

In fact you can easily have __FILE__, __DIR__, and __LINE__ working if instead of doing the usual:

engine.eval(new FileReader("path_to_your_js"));

You actually call a small JS code that load your file:

engine.eval("load('path_to_your_js')");

Upvotes: 4

sja
sja

Reputation: 2392

This is because you probably loaded the script as a String. Most examples are like this:

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

Then the engine does not know, where this script came from, because it only gets the response from the FileReader. It's like calling engine.eval("print('hello')"), there is no file, just a string.

If you call your script from console, using jjs, they're filled correctly.

To achive this from Java, I currently only see a dirty one: Save your file path as string in the context and access this from js:

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

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

The js:

print("I am " + thisFile);

Output:

I am resources/test.js

Note: But it has to be possible, because jdk.nashorn.tools.Shell is able to set up a jdk.nashorn.internal.runtime.Context where this is set in an Array of globals.

Upvotes: 1

Related Questions