Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to execute es6 on java 8 with NashornscriptEngine

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).

like image 387
brain storm Avatar asked Oct 23 '17 21:10

brain storm


2 Answers

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.

like image 73
rmuller Avatar answered Nov 09 '22 00:11

rmuller


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

like image 22
Narasimha Avatar answered Nov 09 '22 00:11

Narasimha