Use Nashorn and WebJars to execute Javascript server-side

Executing javascript inside a browser is one way of leveraging javascript. Node is another way, but on the server-side this time.

Can we do the same thing as Node with Java 8 and Nashorn?

The answer is yes. Let’s see how it works.

The following code compiles coffee script to javascript using java code.

Here’s what it does in details:

  • It loads coffee-script.min.js from the classpath. Here, I used a WebJar to import the script into my project
  • Then it create a Nashorn script engine
  • It compiles the coffee-script.min.js once
  • It executes the compile code on the provided coffee script source

Yeah! Server-side javascript in java!

5 thoughts on “Use Nashorn and WebJars to execute Javascript server-side”

  1. Many thank’s for sharing this info. I tell me if nashorn is very performant compare to Node.js.

    I tell you that because I had a big problem with Rhino (performance and out of memory) when I try to execute some complex javascript. On other words in my I use the javascript inference engine written in Javascript and I need to use it in Java context (for Eclipse completion, etc).

    Whith Rhino, I cannot use tern.js, so I had to developped a Java HTTP Client which starts and communicates with a node.js server and it works like a sharm (very performant and no out of memory).

    1. Angelo, I couldn’t tell you if Nashorn has better performance than Rhino. I just now it was a goal of the project. I’ve had the same problem with Rhino and you basically have to disable the optimisations. This is something I didn’t have to do for Nashorn. I’m currently using it both with coffeescript.js and asciidoctor.js. The later being much bigger. I have no problem.

  2. David,

    En lisant : String script = readScript(“META-INF/resources/webjars/coffee-script/1.7.0/coffee-script.min.js”);
    Je vois que tu as une version décompressée du webjar.
    Qu’est-ce-qui est responsable de cette décompression ? un bout de maven ?

    1. Le jar est dans le classpath. Ensuite, je ne fais que lire cette ressource avec le mécanisme standard. Il se trouve que la ressource est dans un jar, donc compressée, mais c’est transparent pour moi.

Comments are closed.