Accept JS file as argument and support NPM modules via jvm-npm
- HelloNashorn now takes a JS file path as command-line argument - Uses jvm-npm (org.bsc:jvm-npm-core:1.1.0) for require() support - Require.root set to script's parent dir so node_modules resolves correctly - Engine created with -scripting mode for load() support
This commit is contained in:
@@ -9,6 +9,7 @@ repositories {
|
|||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation 'org.openjdk.nashorn:nashorn-core:15.6'
|
implementation 'org.openjdk.nashorn:nashorn-core:15.6'
|
||||||
|
implementation 'org.bsc:jvm-npm-core:1.1.0'
|
||||||
}
|
}
|
||||||
|
|
||||||
application {
|
application {
|
||||||
|
|||||||
@@ -3,18 +3,29 @@ package com.example;
|
|||||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||||
|
|
||||||
import javax.script.ScriptEngine;
|
import javax.script.ScriptEngine;
|
||||||
|
import java.io.File;
|
||||||
|
|
||||||
public class HelloNashorn {
|
public class HelloNashorn {
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
|
if (args.length == 0) {
|
||||||
|
System.err.println("Usage: HelloNashorn <script.js>");
|
||||||
|
System.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
File scriptFile = new File(args[0]).getAbsoluteFile();
|
||||||
|
if (!scriptFile.isFile()) {
|
||||||
|
System.err.println("File not found: " + args[0]);
|
||||||
|
System.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
||||||
ScriptEngine engine = factory.getScriptEngine();
|
ScriptEngine engine = factory.getScriptEngine("-scripting");
|
||||||
|
|
||||||
engine.eval("print('Hello World from JavaScript!')");
|
engine.put("__rootDir", scriptFile.getParent());
|
||||||
|
engine.eval("load('classpath:jvm-npm.js')");
|
||||||
|
engine.eval("Require.root = __rootDir");
|
||||||
|
|
||||||
String result = (String) engine.eval(
|
engine.put("__scriptFile", scriptFile.getAbsolutePath());
|
||||||
"var greeting = 'Hello from Nashorn on JDK ' + java.lang.System.getProperty('java.version');" +
|
engine.eval("load(__scriptFile)");
|
||||||
"greeting"
|
|
||||||
);
|
|
||||||
System.out.println(result);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user