Is it possible to import javascript files to a java ScriptEngine - Stack Overflow

I am using nashorn java ScriptEngine. I would like to evaluate a script which includes other scripts. I

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

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

Share Improve this question asked Jul 15, 2017 at 9:47 JoelJoel 6899 silver badges29 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Actually I found the answer myself: as mentioned in the ment, 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.

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744955613a4603175.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信