Redirect Nashorn stdout and stderror

998 Views Asked by At

Trying to redirect the Nashorn scripting engine from within a Java class. This is how I'm initializing it right now. I'd like to redirect any output from the scripts the engine runs.

String[] nashornArgs = new String[] {"-strict", "--no-java",
                "--no-syntax-extensions", "-dump-on-error"};
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine(nashornArgs);

I know Nashorn has the following args (below) but I'm not sure how to initialize correctly and in a manner where any output is discarded by the program. Maybe create a temp file and then delete the temp file once the engine is done? Seems messy to me.


--stderr (Redirect stderr to a filename or to another tty, e.g. stdout)

param: output console

--stdout (Redirect stdout to a filename or to another tty, e.g. stderr)

param: output console

1

There are 1 best solutions below

4
On BEST ANSWER

You can redirect output like this:

package com.example;

import java.io.StringWriter;

import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

import jdk.nashorn.api.scripting.NashornScriptEngineFactory;

public class Nashorn {
    public static void main(String[] args) throws ScriptException {
        String[] arguments = new String[] {"-strict", "--no-java", "--no-syntax-extensions", "-dump-on-error"};
        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
        ScriptEngine engine = factory.getScriptEngine(arguments);
        StringWriter sw = new StringWriter();
        ScriptContext context = engine.getContext();
        context.setWriter(sw);
        context.setErrorWriter(sw);
        engine.eval("print('hello world')");
        System.out.println("redirected output: " + sw);
    }
}