
【JDK8】JavaScript 引擎 Nashorn 之 jjs
在安裝完 JDK8,並設定好 print('Hello, World'); 看!第一個 Java 程式就是這麼簡單,接著開啟命令列,切換到 hello.js 所在目錄,使用 > jjs hello.js Hello, World (這不是 Java 啊!啊!啊!啊!… XD) 被識破了嗎??JDK8 包括了一個新的 JavaScript 引擎 Nashorn,你可以使用命令列工具 這篇文章,要先來談談,命令列工具 >jjs jjs> print('Hello, World') Hello, World jjs> 1 + 2 3 jjs> [1, 2, 3].join(', '); 1, 2, 3 jjs> exit() 如果要在目前 .js 檔案中,載入其他 .js 檔案,可以使用 load('http://openhome.cc/Gossip/JavaScript/samples/js/gossip-0.1.js'); XD.each(['a', 'b', 'c'], function(elem) { print(elem); }); 嚴格模式Nashorn 引擎是基於 ECMAScript 5.1,未來的 Nashorn 版本可望支援 ECMAScript 6,因而基本上,在〈JavaScript 語言核心〉 系列中介紹到 ECMAScript 5,Nashorn 都可以支援,像是 嚴格模式,你也可以在執行 name = 'Justin'; print('Hello, ' + name); 如下執行時就會發生錯誤,因為 ECMAScript 5 嚴格模式下,變數必須使用 >jjs -strict hello.js hello.js:1 ReferenceError: "name" is not defined scripting 模式執行 例如,JavaScript 本身對 var name = 'Justin'; print('Hello, ${name}'); print("Hello, ${name}"); print("Hello, ${name.toUpperCase()}"); 執行結果如下: >jjs -scripting hello.js Hello, ${name} Hello, Justin Hello, JUSTIN scripting 模式下,多了一些全域變數可以使用,例如,可以使用 $ARG.forEach(function(elem, index) { print("index: ${index}, elem: ${elem}"); }); 指定命令列引數時,除了加上 >jjs -scripting hello.js -- 1 2 3 index: 0, elem: 1 index: 1, elem: 2 index: 2, elem: 3 在不使用 在加上 for(var prop in $ENV) { print("${prop}: ${$ENV[prop]}"); } 以下是一個執行範例與結果顯示片段: >jjs -scripting hello.js USERDOMAIN_ROAMINGPROFILE: Justin-2012 LOCALAPPDATA: C:\Users\Justin\AppData\Local PROCESSOR_LEVEL: 6 FP_NO_HOST_CHECK: NO USERDOMAIN: Justin-2012 LOGONSERVER: \\JUSTIN-2012 PROMPT: $P$G SESSIONNAME: Console 略... 如果想執行外部指令,可以使用 var fileName = readLine('Input a filename: '); var content = readFully(fileName); echo(content); 執行結果範例如下: >jjs -scripting hello.js Input a filename: hello.js var fileName = readLine('Input a filename: '); var content = readFully(fileName); echo(content);
scripting 模式下,可以撰寫 HereDoc,也就是多行字串,直接來看個範例就知道怎麼撰寫: # var doc = <<DOC Hello, ${arguments[0]}. This is heredoc example. Try it! DOC print(doc);
>jjs hello.js -- Justin Hello, Justin. This is heredoc example. Try it! 更多 Nashorn 的 scripting 模式說明,還可以參考〈Nashorn and Shell Scripting〉。
後續還有兩篇文章,會來介紹如何使用 JavaScript 呼叫 Java API。 |