Enable scripting mode for nashorn in java

I need to execute some bash shell commands from Java using nashorn.

I have a javascript file:

#!/usr/bin/jjs

var testBashMethod = function(name){

    $EXEC("echo Hello from bash ${name}");
};

testBashMethod("foobar");

      

I have a java method loading the above javascript method into the Nashorn engine and executing it:

public void executeScript(){

    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine = engineManager.getEngineByName("nashorn");

    engine.eval(new FileReader("script.js"));

    Invocable invocable = (Invocable)engine;
    invocable.invokeFunction("testBashMethod");
}

      

When executing the above method, I am getting the following error:

jdk.nashorn.internal.runtime.ECMAException: ReferenceError: "$EXEC" is not defined

      

I am assuming I need to load the nashorn engine in scripting mode in java. On the terminal, I can start the engine with scripting mode, after which the following is done:

jjs -scripting
jjs> $EXEC('echo Hello World..!!')

      

My question is: How do I load the nashorn engine in Java in scripted mode? so bash scripting methods are available. Or is there something else that I am missing.

Thanks for the help.

+3


source to share


2 answers


NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getEngine(new String[] { "-scripting" });

      



See the Nashorn Wiki for more documentation. I got (and modified) the above snippet from the Nashorn jsr223 engine page .

+9


source


You can also define nashorn options using the System property and nashorn.args. So something like

java -Dnashorn.args = -scripting MyMainClass



will work and your code can stick to the javax.script API (no need to use the jdk.nashorn.api.scripting API). But this means that all engines built by your Java process will have a scripting mode.

+1


source







All Articles