November 18, 2017

Java 8 Nashorn Using JavaScript on the JVM

Nashorn is the official JavaScript Engine in the Java Virtual Machine since Version 8. It supports and implements the ECMAScript 5.1 specification and competes among others directly with Google V8 (the script engine behind Node.js). Nashorn compiles JavaScript to Java Bytecode during runtime and thus provides high interoperability of Java and JavaScript.

Lets give it a try with our previous example in Java EE 7 Implementing Statistics with Interceptor, CDI Observes and LongSummaryStatistics

#!/usr/bin/jjs -fv

var uri = "http://localhost:8080/example-javaee7/rest/statistics"
var command = "curl ${uri}"
var result = $OUT
var resultAsArray = JSON.parse(result)

Now call it

$ chmod +x nashorn-demo.js
$ ./nashorn-demo.js 
nashorn full version 1.8.0_151-8u151-b12-0ubuntu0.16.04.2-b12
{"statistics":"LongSummaryStatistics{count=18, sum=111, min=0, average=6.166667, max=75}"}
[object Object]

No comments: