'How to use ScriptEngine to runtime compile js in native-image

graalvm version: openjdk version "17.0.2" 2022-01-18 OpenJDK Runtime Environment GraalVM CE 22.0.0.2 (build 17.0.2+8-jvmci-22.0-b05) OpenJDK 64-Bit Server VM GraalVM CE 22.0.0.2 (build 17.0.2+8-jvmci-22.0-b05, mixed mode, sharing)

OS: win10

Q:I want to use native-image to build my project. When Build,I don't any error.But when I running,It will show me

ERROR: [Script Manager] Exception occurred. Path: test.js
Exception: java.lang.NullPointerException

my method

protected Invocable getInvocable(String path) {
    String truePath = ScriptPath(path);
    try {
        File scriptFile = new File(ScriptPath(path));
        String scriptStr = new String(Files.readAllBytes(scriptFile.toPath()), StandardCharsets.UTF_8);

        // Nashorn
        // CompiledScript compiledScript = ((NashornScriptEngine)
        // engine).compile(scriptStr);

        // graal
        ScriptEngine graalEngine = new ScriptEngineManager().getEngineByName("js");
        CompiledScript compiledScript = ((Compilable) graalEngine).compile(scriptStr);

        if (compiledScript == null)
            return null;
        compiledScript.eval();
        return (Invocable) compiledScript.getEngine();
    } catch (Exception e) {
        Logger.error("[Script Manager] Exception occurred. Path: " + path + "\r\nException: " + e);
        return null;
    }
}

my build args

--no-fallback
--verbose
--initialize-at-build-time=org.slf4j.LoggerFactory
--initialize-at-build-time=org.apache.logging.slf4j.Log4jLogger
--initialize-at-run-time=io.netty.util.internal.logging.Log4JLogger
--initialize-at-run-time=io.netty.util.internal.logging.Slf4JLoggerFactory$NopInstanceHolder
--enable-url-protocols=http
--enable-url-protocols=https
--allow-incomplete-classpath
-J-Duser.language=zh_TW
-H:+AddAllCharsets
-H:+ReportExceptionStackTraces
--report-unsupported-elements-at-runtime
-Dpolyglot.js.nashorn-compat=true
-Dfile.encoding=UTF-8
--language:js

I read a lot of article,but no one is about read file from local path. I want know how can I do to let code can Compile js in runtime. It work in jar very well. please!thanks every friends~



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source