2

I have tried to call javascript function from java code, but I am getting the following error while using javascript API:

Caused by: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "File" is not defined. (#8) at sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3770) at sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3748) at sun.org.mozilla.javascript.internal.ScriptRuntime.notFoundError(ScriptRuntime.java:3833) at sun.org.mozilla.javascript.internal.ScriptRuntime.name(ScriptRuntime.java:1760) at sun.org.mozilla.javascript.internal.Interpreter.interpretLoop(Interpreter.java:1785) at sun.org.mozilla.javascript.internal.Interpreter.interpret(Interpreter.java:849)

java code:

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    engine.eval(Files.newBufferedReader(Paths.get("D:/test/test.js"), StandardCharsets.UTF_8));
    Invocable inv = (Invocable) engine;

    inv.invokeFunction("display", "test");
    inv.invokeFunction("writeTextFile", "D:\\test\\file.txt", "test");

test.js:

var display = function(name) {
    print("Hello, I am a Javascript display function "+name);
    return "display function return"
}

function writeTextFile(afilename, output) {
    var txtFile = new File(afilename);
    txtFile.writeln(output);
    txtFile.close();
}

display function working fine, the error appear while executing writeTextFile function.

4

1 Answer 1

0

in your test.js, try:

var txtFile = new File([""], afilename);
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, same error. I seems my missing is the JavaScript libraries as File can't be defined well.
I don't think you will be able to write a file to the local filesystem using javascript called via script engine. See w3c.github.io/FileAPI for more info (and comments about restrictions and compatibility). And also discussion at stackoverflow.com/questions/461791/… This is essentially a huge security hole, if you execute a script in your java app and someone replaces it with malicious that writes to user disk without approval. Most browsers don't allow you to write to user's disk.
As a work around, call "display", get result and then use Java to create the file for you instead of JavaScript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.