Friday, September 4, 2015

Oracle Nashorn! The Node.js on JVM

Oracle Nashorn: A Next-Generation JavaScript Engine for the JVM


Nashorn is the new JavaScript Runtime that comes with Java 8 and runs on the JVM.

In this post we will see how to run simple 
Node.js applications with Nashorn on the JVM.

Avatar.js is a project to bring the node programming model, APIs and module ecosystem to the Java platform. Unfortunately Avatar.js does not officially provide a binary distribution and the build process looks quite intricate (involving Python and C++).

There is also 
Project Avatar, an upcoming web-platform by Oracle. Project Avatar builds uponAvatar.js.

By reverse-engineering Project Avatar I found the necessary artefacts of Avatar.js in the java.net Maven repository. These artefacts can be used to run Node applications with Avatar.js without having to build Avatar.js yourself.

The following steps show how to run a simple Node.js web application on OSX. The steps should be very similar for Linux or Windows.

1.            Download avatar-js.jar from the java.net Maven Repo.
Current version is here:https://maven.java.net/content/repositories/public/com/oracle/avatar-js/0.10.25-SNAPSHOT/
Example file: avatar-js-0.10.25-20140313.063039-43.jar 

2.            Download the native library avatar-js.dylib from the java.net Maven Repo.
Current version is here:https://maven.java.net/content/repositories/public/com/oracle/libavatar-js-macosx-x64/0.10.25-SNAPSHOT/
Example file: libavatar-js-macosx-x64-0.10.25-20140312.062209-35.dylib
For Linux you would download the corresponding 
.so file from ../libavatar-js-linux-x64/0.10.25-SNAPSHOT/
For Windows you would download the corresponding 
.dll file from ../libavatar-js-win-x64/0.10.25-SNAPSHOT/

3.            Rename the native library to avatar-js.dylib and rename the jar to avatar-js.jarand put both in a directory called dist

4.            Create a simple Node.js app in the a file called app.js:

var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

Run the command: 
java -Djava.library.path=dist -jar dist/avatar-js.jar app.js

  1. The output should be: Server running at http://127.0.0.1:8000/ 
  2.  Navigate to  http://localhost:8000/

No comments:

Post a Comment

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...