目前nodejs调用jar主要有两种方式:
方法一(子进程运行):
const { spawn } = require('child_process'); const child = spawn('java', ['-jar', `${__dirname}/Main.jar`]); child.stdout.on('data', (data) => { console.log(`child stdout: ${data}`) }); child.stderr.on('data', (data) => { console.error(`stderror ${data}`); }); child.on('exit', function(code, signal){ console.log('child process exited with' + `code ${code} and signal ${signal}`); });
在makefile文件目录下执行make打包Main.jar
. ├── Main.java ├── makefile └── manifest.txt
makefile
JFLAGS = -g JC = javac JAR = jar JARFLAGS = cvfe .SUFFIXES: .java .class .jar .java.class: $(JC) $(JFLAGS) $*.java .class.jar: $(JAR) $(JARFLAGS) Main.jar Main *.class CLASSES = \ Main.java default: jar classes: $(CLASSES:.java=.class) jar: $(CLASSES:.java=.jar) clean: $(RM) *.class $(RM) *.jar%
manifest.txt
Main-Class: Main%
Main.java
package com.lablelan; public class Hello { public static void main(String[] args) { System.out.println("hello world"); } }
输出结果:
child stdout: hello world child process exited withcode 0 and signal null
方法二(通过c++桥接):
var java = require('java'); var javaLangSystem = java.import('java.lang.System'); var num = java.newLong(100); // 函数以Sync结尾会运行在v8主线程 javaLangSystem.out.printlnSync('Hello World'); // 函数不带Sync将会运行在v8的非主线程的工作线程 num.toString((err, data)=>{ console.log("data: ", data) }) // process.exit(0);
安装环境
# 注意这里需要有java8环境,如果报错找不到./build/jvm_dll_path.json可以执行node_modules/java/postInstall.js生成 # 出现安装问题可以参考 https://github.com/joeferner/node-java npm install -g node-gyp npm install java
输出结果
Hello World data: 100