admin管理员组

文章数量:1401672

I have 6 js files and I need to include them all into final script to pass ScriptEngine's eval method.How can I do it? ScriptEngine haven't add() method.I can read them with FileReader and than concatenate those strings but I think there will be a better way.

I have 6 js files and I need to include them all into final script to pass ScriptEngine's eval method.How can I do it? ScriptEngine haven't add() method.I can read them with FileReader and than concatenate those strings but I think there will be a better way.

Share Improve this question asked Nov 11, 2011 at 12:26 shift66shift66 12k13 gold badges53 silver badges83 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

You can use the overload eval(Reader) to avoid having to load scripts into a String yourself.

You could use one script to call the other 6 scripts.

Example:

function callOtherFunctions() {
   functionOne();
   functionTwo();
   .
   .
   .
   functionSix();
}

Not 100% sure how good that solution will work but it will call all other 6 functions.

Run eval multiple times using the same ScriptContext.

In the next example I need to run Utils.js script before running MainScript.js because Utils.js is defining some functions I need in MainScript.js, I always think of this order as the way these scripts will appear in an HTML page of I were to execute this in a browser:

    String scriptsUtilsFilePath = "src/test/resources/scripts/Utils.js";
    String mainScriptFilePath = "src/test/resources/scripts/MainScript.js";

    // Get the script engine manager
    ScriptContext newContext = new SimpleScriptContext();
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("nashorn");// Newest Javascript engine

    // Run Utils
    engine.eval(new FileReader(scriptsUtilsFilePath), newContext);

    // Run the Main Script
    engine.eval(new FileReader(mainScriptFilePath), newContext);

本文标签: javaHow to make ScriptEngine to run multiple javascript filesStack Overflow