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!