I am trying to execute a javascript (ES6) function in java 8 (1.8.0_102).
Here is snippet javascript trimmed down.
const myfunc = (args) => {
if (!(args.name || args.zip))
return
const result = {...args}
const { name, zip, date } = result
...
}
Here is my java code
public static Object processArbitraryJavaScript(String params)
{
String[] options = new String[] {"--language=es6"};
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
NashornScriptEngine engine = (NashornScriptEngine) factory.getScriptEngine(options);
Object result = null;
try
{
engine.eval(new FileReader("sample.js"));
Invocable inv = (Invocable) engine;
result = inv.invokeFunction("myfunc", params);
}
catch (ScriptException scriptException )
{
LOGGER.error(
"ScriptException encountered trying to write arbitrary JavaScript"
+ scriptException.toString());
}
catch (NoSuchMethodException e) {
LOGGER.error(
"No such Method");
}
return result;
}
I had written a unit test that passes params. when I execute the test, I get this exception
ScriptException encountered trying to write arbitrary JavaScriptjavax.script.ScriptException: <eval>:2:5 Expected : but found (
if (!(args.name || args.zip))
^ in <eval> at line number 2 at column number 5
I commented out the if
statement in javascript but seeing futher errors down the code.
ScriptException encountered trying to write arbitrary JavaScriptjavax.script.ScriptException: <eval>:5:8 Expected : but found result
const result = {...args}
^ in <eval> at line number 5 at column number 8
again further down, I see this error
ScriptException encountered trying to write arbitrary JavaScriptjavax.script.ScriptException: <eval>:6:6 Expected: but found {
const { name, zip, date } = result
^ in <eval> at line number 6 at column number 6
I am thinking this my scriptEngine is reading the script as ES6.
what am I doing wrong here?
(btw, the script works fine in JS).
Nashorn @Java8_u40+ only supports a limited number of ES6 features. It's more ES5+ than ES6. See JEP 292: Implement Selected ECMAScript 6 Features in Nashorn
Arrow functions are schedules for Java 9 update releases.
As per the documentation, we can enable ES6 mode by supplying a jvm option: ["-Dnashorn.args=--language=es6"]
Refer https://developer.oracle.com/databases/nashorn-javascript-part2.html
This works with JDK 8 as well though functionality will be limited
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With