Node JS application running on GraalVM — interoperating with Java, Python, R and more
In this article, I will take a brief look at running Node applications on GraalVM and specifically their polyglot interaction on GraalVM with other languages, specifically Java, Python and R (only scratching the surface).
Polyglot Node Application calling out to Java
The sample application under scrutiny is a Node application that makes use of a Java Class provided in a JAR file. The Java Class — Joker — returns jokes from a getJoke() method or as String from a getJokes() method.
The Java Class can be tried out:
java -cp application-bundle.jar nl.amis.js2java.Joker
The Node application is implemented in Joker2.js. It is very straightforward. The Java Class is loaded with the Java.type call. Subsequently, a single Joker object is instantiated with the new statement. In function getJoke(), a call is made to the getJoke() method on javaJoker1 — the Java method that returns a random element from the jokes collection.
The application can be run with this command line:
node -jvm -vm.cp application-bundle.jar joker2.js
This is visualized as follows:
The program flow at runtime can be visualized as follows:
Polyglot Node Application embedding Python, Ruby and R
A Node application running on GraalVM can evaluate embedded, inline code snippets and also load sources from file. These code snippets and source can be defined in all languages that through Truffle parsing can run on GraalVM; these include Ruby, R, Python and LLVM languages (such as C, C++, Fortran, Rest and Swift). The node application should be run with the -polyglot command line switch, to engage the polyglot interoperability features.
The file is executed with this command
js -polyglot -jvm polyglot.js
The class is bundled in the same application-bundle.jar file we saw before, including the validator-bundled.js file that it loads at runtime.
The salient part of the Node application that leverages the Postal Code capabilities of the Java Class is shown below:
GitHub Repository with sources for this article: https://github.com/AMIS-Services/jfall2019-graalvm
GitHub Home of GraalJS — https://github.com/graalvm/graaljs
JavaDocs for GraalVM Polyglot — https://www.graalvm.org/truffle/javadoc/org/graalvm/polyglot/package-summary.html
Originally published at https://technology.amis.nl on November 5, 2019.