Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  148] [ 2]  / answers: 1 / hits: 16372  / 9 Years ago, sat, march 14, 2015, 12:00:00

Is it possible to include one js from another with java nashorn engine?



ScriptEngine engine = new ScriptEngineManager().getEngineByName(Nashorn);
InputStreamReader rs = new InputStreamReader(new FileInputStream(new File(.../script.js));
engine.eval(rs);


script.js



var System = Java.type('java.lang.System');
// document.write(./test.js); - javax.script.ScriptException: ReferenceError: document is not defined
// require('./test.js'); - require is not defined


test.js



System.out.println(reading test.js file);


i want to create top level script (in this example its script.js) and use it as a library for other scripts in same directory.


More From » java

 Answers
12

you can use Nashorn's load() function



https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions



// can load script from files, URLs

load(foo.js); // loads script from file foo.js from current directory
load(http://www.example.com/t.js); // loads script file from given URL

// loads script from an object's properties.

// Object should have script and name properties.
// script property contains string code of the script.
// name property specifies name to be used while reporting errors from script
// This is almost like the standard eval except that it associates a name with
// the script string for debugging purpose.

load({ script: print('hello'), name: myscript.js})

// load can also load from pseudo URLs like nashorn:, fx:. nashorn: pseudo URL scheme
// for nashorn's built-in scripts. fx: pseudo URL scheme for JavaFX support scripts

// load nashorn's parser support script - defines 'parse'
// function in global scope

load(nashorn:parser.js);

// load Mozilla compatibility script - which defines global functions
// like importPackage, importClass for rhino compatibility.

load(nashorn:mozilla_compat.js);

[#67436] Thursday, March 12, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gregorio

Total Points: 362
Total Questions: 95
Total Answers: 93

Location: Puerto Rico
Member since Sun, Jun 27, 2021
3 Years ago
;