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 {
|
||||
implementation 'org.openjdk.nashorn:nashorn-core:15.6'
|
||||
implementation 'org.bsc:jvm-npm-core:1.1.0'
|
||||
}
|
||||
|
||||
application {
|
||||
|
||||
@@ -3,18 +3,29 @@ package com.example;
|
||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
|
||||
import javax.script.ScriptEngine;
|
||||
import java.io.File;
|
||||
|
||||
public class HelloNashorn {
|
||||
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();
|
||||
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(
|
||||
"var greeting = 'Hello from Nashorn on JDK ' + java.lang.System.getProperty('java.version');" +
|
||||
"greeting"
|
||||
);
|
||||
System.out.println(result);
|
||||
engine.put("__scriptFile", scriptFile.getAbsolutePath());
|
||||
engine.eval("load(__scriptFile)");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user