Nashorn is a JavaScript engine developed in Java by Oracle, and has been released with Java 8. Nashorn allows embedding Javascript in Java applications via JSR-223 and allows to develop standalone Javascript applications, and it provides better runtime performance and better compliance with the ECMA normalized Javascript specification.
Java 8 introduces new command-line tool called jjs, for executing JavaScript. It can be found in the bin/ folder of a JDK installation along with the well-known java, javac, or jar tools.
The jjs tool accepts a list of JavaScript source code files as arguments.
Please note this program run in JDK version 8 or greater.
package com.pwn.js;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class ExecuteJS {
public static void main(String[] args) {
// Obtain an instance of the JavaScript engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
/*
* hello.js source code
* var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
* var evenNumbers = array.filter(function(i) { return i % 2 == 0; });
* print('Output from JS file ',evenNumbers);
*/
// Load and execute a script from the file 'hello.js'
try {
engine.eval(
new FileReader(new File("c://install/hello.js")));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (ScriptException ex) {
ex.printStackTrace();
}
}
}
Output from JS file 2,4,6,8,10