I am trying to use a transpiling tool that has been developed in js and was available in GitHub. This transpiler is capable to convert the javascript code to java.
I want to call the tool via java code so that I could read js files in java and process them using the transpiler developed in JS. The tool is using 'const' as part of its code. While using ScriptEngine it gives me an exception. Please help!!
Sample Code:
public static void main(String[] args) {
ScriptEngineManager manager = null;
ScriptEngine engine = null;
File folder = null;
try {
manager = new ScriptEngineManager();
engine = manager.getEngineByName("nashorn");
String testConst1 = (String) "const pi = 3.14;";
String testPrint1 = (String) "function hello(name) {print ('Hello, ' + name +' = '+ pi);}";
engine.eval(testConst1);
engine.eval(testPrint1);
Invocable inv = (Invocable) engine;
inv.invokeFunction("hello", "pi");
// System.out.println(); //This one works.
} catch (Exception e) {
e.printStackTrace();
}
}
This piece of code gives me below stack trace.
javax.script.ScriptException: <eval>:1:0 Expected an operand but found const
const pi = 3.14;
^ in <eval> at line number 1 at column number 0
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:455)
at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:522)
at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:509)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:397)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:152)
at javax.script.AbstractScriptEngine.eval(Unknown Source)
Caused by: jdk.nashorn.internal.runtime.ParserException: <eval>:1:0 Expected an operand but found const
const pi = 3.14;
^
at jdk.nashorn.internal.parser.AbstractParser.error(AbstractParser.java:292)
at jdk.nashorn.internal.parser.AbstractParser.error(AbstractParser.java:277)
at jdk.nashorn.internal.parser.Parser.unaryExpression(Parser.java:3175)
at jdk.nashorn.internal.parser.Parser.expression(Parser.java:3275)
at jdk.nashorn.internal.parser.Parser.expressionStatement(Parser.java:1152)
at jdk.nashorn.internal.parser.Parser.statement(Parser.java:969)
at jdk.nashorn.internal.parser.Parser.sourceElements(Parser.java:775)
at jdk.nashorn.internal.parser.Parser.program(Parser.java:711)
at jdk.nashorn.internal.parser.Parser.parse(Parser.java:284)
at jdk.nashorn.internal.parser.Parser.parse(Parser.java:250)
at jdk.nashorn.internal.runtime.Context.compile(Context.java:1207)
at jdk.nashorn.internal.runtime.Context.compileScript(Context.java:1179)
at jdk.nashorn.internal.runtime.Context.compileScript(Context.java:594)
at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:520)
... 5 more