最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论