2

I am using nashorn java ScriptEngine. I would like to evaluate a script which includes other scripts. I know I can use the load directive directly in the javascript itself, but I would prefer to import or load it directly from the java code instanciating the scriptEngine. Is there a way to do this ? Something like :

void evaluateScript(String scriptName, String dependency) {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine jsEngine = factory.getEngineByName("nashorn");
    jsEngine.load(depency); // does not exist.
    jsEngine.eval();
}

I see the "load" function does not exist. How could I achieve this?

Thanks

2 Answers 2

5

Actually I found the answer myself: as mentioned in the comment, it is possible to call several eval with different scripts, same engine, and the engine will keep the evaluated scripts in its context. So here is my code:

public void executeScript(String scriptName, String[] dependencies) {
    try {
        FileReader script = new FileReader(scriptName);
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine jsEngine = factory.getEngineByName("nashorn");

        if(dependencies != null) {
            for (String dependency : dependencies) {
                FileReader dependencyFile = new FileReader(dependency);
                jsEngine.eval(dependencyFile);
            }
        }

        jsEngine.eval(script);
    }
}

I can define functions in my dependencies and use them in the script of name scriptName.

Sign up to request clarification or add additional context in comments.

Comments

0

javax.script.ScriptEngine has many "eval" methods - there are java.io.Reader accepting eval methods like this -> eval

You can pass a java.io.FileReader or a jdk.nashorn.api.scripting.URLReader to load script from a file or a URL.

2 Comments

Hello, thanks for the answer but it does not fit my question: I want to execute one script theScript, together with other scripts otherScriptList. But I will try eval on different scripts with the same engine and check if the engine keeps the previous ones in his context.
Yes, same engine keeps "context"!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.