【问题标题】:Java, nashorn accessing another js fileJava,nashorn访问另一个js文件
【发布时间】:2015-05-17 01:41:55
【问题描述】:

是否可以使用 java nashorn 引擎包含一个来自另一个的 js?

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

我想创建顶级脚本(在本例中为它的 script.js)并将其用作同一目录中其他脚本的库。

【问题讨论】:

  • 你的ScriptEngine应该以“nashorn”的名字获取,而不是“nashorn”

标签: java javascript scope nashorn


【解决方案1】:

你可以使用 Nashorn 的 load() 函数

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

【讨论】:

    【解决方案2】:

    Nashorn 很棒。

    并且自带内置加载方法!!!

    load 可以获取 URL,因此您可以利用 CDNJS 上的优秀 JavaScript 库

    如果您使用nudge4j,您可以获得kangax's html minifier 像这样运行:

    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 });
    

    【讨论】:

      猜你喜欢
      • 2011-10-06
      • 2020-08-25
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2023-04-04
      • 2018-09-26
      相关资源
      最近更新 更多