Search code examples
nashorn

Nashorn : how to evaluate scripts in scripting mode


Im starting to explore jdk 8 new javascript engine nashorn and wanted to build some automating task scripts. I ve an issue, ive no idea how to evaluate a js file in scripting mode from javascript, using engine.eval() eg .

p.s: im not talking about jjs -scripting which is good but only works one way. I want the other way; make the engine evaluate in scripting mode from java


Solution

  • After a lot of head scratching, i came up with a trick where i can actually launch my script's execution through a command line from a hand crafted System Process :

    //tricking the nashorn engine with jjs command
        public void evalScriptInScriptingMode(String fileName)
        {
            String[] args = new String[]{"jjs", "-scripting", fileName};
    
            //This class is used to create operating system processes
            ProcessBuilder pb = new ProcessBuilder(args);
    
            pb.directory(null);
    
            File log = new File("jjs_log.txt");
    
            int i = 0;
    
            while(log.exists())
            {
                i++;
                log = new File("jjs" + i + "_log.txt");
            }
    
    
            pb.redirectErrorStream(true);
            pb.redirectOutput(ProcessBuilder.Redirect.appendTo(log));
            Process p = null;
    
            try
            {
                p = pb.start();    //start the process which remains open
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }