【问题标题】:Run a Java Function through NodeJS通过 NodeJS 运行 Java 函数
【发布时间】:2020-03-31 14:38:15
【问题描述】:
我有一个向我的 Express 服务器发送字符串和整数的表单数据,我需要使用我的 Java 后端进行计算和对前端的响应,我可以直接从 Express 服务器执行此操作,还是需要涉及其他步骤?
【问题讨论】:
-
GraalVM 允许您直接在 javascript 中使用 java,如果您不想像其他答案建议的那样使用 exec。
标签:
javascript
java
node.js
express
【解决方案1】:
您可以从 nodejs 执行 java 命令。您可以通过 expressjs 路由器运行 exec 命令。对于最好的情况,我会使用 Java 创建另一个 API 并向该端点(微服务)发出请求。但如果你不想这样做,你可以试试这个代码示例;
const express = require('express')
const app = express()
const port = 3000
const exec = require('child_process').exec
app.get('/', (req, res) => {
const child = exec('/usr/bin/java ~/example.jar', => (error, stdout, stderr) {
if (err) {
console.error(err);
res.json({error: err, status: 500, errorOutput: stderr})
return
}
// it is important to have json structure in your output or you need to create a logic which parse the output
res.json(stdout)
})
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
【解决方案2】:
您可以像这样使用 Node.js 'exec' 调用外部 Java 程序:
Javascript 程序
const exec = require('child_process').exec;
// Number 7 is a command line argument to pass to the Java program
exec('java MyJavaApplication 7', function callback(error, stdout, stderr){
console.log(stdout);
});
Java 程序
public class MyJavaApplication {
public static void main(String[] args) {
int input = Integer.parseInt(args[0]);
int output = calculate(input);
System.out.println(Integer.toString(output));
}
private static int calculate(int input) {
// Do some complex calculation
return input * input;
}
}
在 Node.js 上,您可以捕获 Java 程序写入标准输出的任何内容。
根据输入的复杂程度,您可能希望将文件名作为参数传递给 Java 程序。例如,该文件可以具有 JSON 格式的输入内容。