为了账号安全,请及时绑定邮箱和手机立即绑定

通过 NodeJS 运行 Java 函数

通过 NodeJS 运行 Java 函数

慕盖茨4494581 2022-06-09 11:20:15
我有一个表单数据向我的 Express 服务器发送字符串和整数,我需要使用我的 Java 后端进行计算和对前端的响应,我可以直接从 Express 服务器执行此操作,还是需要涉及其他步骤?
查看完整描述

2 回答

?
12345678_0001

TA贡献1802条经验 获得超5个赞

您可以使用 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 格式的输入内容。


查看完整回答
反对 回复 2022-06-09
?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

您可以从 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}!`)) 


查看完整回答
反对 回复 2022-06-09
  • 2 回答
  • 0 关注
  • 391 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号