2015-03-14 9 views
7

Ist es möglich, ein js von einem anderen mit Java Nashorn-Engine zu integrieren?Java, nashorn Zugriff auf eine andere js-Datei

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 Top-Level-Skript erstellt werden soll (in diesem Beispiel seiner script.js) und als Bibliothek verwendet für andere Skripte im selben Verzeichnis.

Antwort

13

können Sie Nashorn der load() Funktion

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"); 
0

Nashorn ist brillant verwenden.

Und es kommt mit der eingebaute load methode !!!

Last kann eine URL nehmen, so dass Sie große JavaScript-Bibliotheken auf dem CDNJS

ausnutzen können, wenn Sie nudge4j verwenden, können Sie bekommen kangax's html minifier wie diese ausgeführt wird:

load('https://cdnjs.cloudflare.com/ajax/libs/html-minifier/3.3.3/htmlminifier.js') 
minify = require('html-minifier').minify; 
input = '<div> <p> foo </p> </div>'; 
output = minify(input, { collapseWhitespace: true });