Hi,
You can file name using ScriptEngine.FILENAME
(http://docs.oracle.com/javase/8/docs/api/javax/script/ScriptEngine.html) property
to associate script "file" name with a eval-ed script.
import javax.script.*;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
e.put(ScriptEngine.FILENAME, "file.js");
e.eval("foo");
}
}
With that Nashorn will associate provided scriptName for that script.
You can use "load" function as well to load a named script from a script
object.
import javax.script.*;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
e.put("scriptName", "file.js");
e.put("script", "foo");
e.eval("load({ script: script, name: scriptName })");
}
}
You can also use "eval naming" (See
http://bugs.java.com/view_bug.do?bug_id=8032068) with jdk8u20+ and the
example below:
import javax.script.*;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
// older form of the directive //@ sourceURL works too.
e.eval("//# sourceURL=myscript.js\nfoo");
}
}
Hope this helps.
-Sundar
On Wednesday 09 July 2014 08:32 PM, Tim Fox wrote:
Hi folks,
I am using Nashorn to execute a piece of JavaScript using eval:
String str = loadFileFromClasspath(scriptName);
engine.eval(str);
If there's an error in the script, I get an error message something
like this:
ReferenceError: "blah" is not defined in <eval> at line number 1245242
Is there any way informing the engine of the "script name" when
running the eval so it provides nicer error messages like this:
ReferenceError: "blah" is not defined in myscript.js at line number
1245242
Which is much nicer for the user.
(As a last resort I can catch any exceptions and replace <eval> with
scriptName then rethrow them, but it would be nice if the engine could
do this for me)