halloleo
halloleo

Reputation: 10354

In the Nashorn JavaScript engine, how can I read a file from the file system?

In the Nashorn JavaScript engine, how can I read a file from the file system? In node.js I use

fs = require('fs');
var content = fs.readFileSync("sometext.txt")

but in Nashorn this gives already an exception on the require statement.

Upvotes: 0

Views: 1535

Answers (1)

halloleo
halloleo

Reputation: 10354

You have two options:

1 Use the Scripting API

The Nashorn engine can be started with the -scripting flag. Once you've done this, you can use the JS function readFully to read the content of a file into a variable.

Instantiate the Nashorn engine and use it as follows (Java code):

NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine(new String[] { "-scripting" });
        
engine.eval(new FileReader("myscript.js"));

where the JavaScript file contains:

...
var content = readFully("mytext.txt")
...

2 Use the Java API

Read the file in JavaScript via calls to the classes/functions in java.nio.file and then convert the resulting Java bytes object to JavaScript.

Instantiate the Nashorn engine in the normal manner (Java code):

ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn");
    
engine.eval(new FileReader("myscript.js"));

and put in the JavaScript file myscript.js:

var pathObj = java.nio.file.Paths.get("mytext.txt")
var bytesObj = java.nio.file.Files.readAllBytes(pathObj);

var bytes = Java.from(bytesObj) // converting to JavaScript

var content = String.fromCharCode.apply(null, bytes)

Upvotes: 2

Related Questions