如何从NodeJs调用Java程序 [英] How to call Java program from NodeJs

查看:1452
本文介绍了如何从NodeJs调用Java程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java程序,通常从命令行启动.从命令行启动后,Java程序将一直运行直到按下Ctrl + C退出该程序或杀死另一个脚本中的命令为止. Java程序会向控制台输出错误消息.

I have a Java program that I normally start from command line. After starting from command line, the java program keeps running forever until Ctrl+C is pressed to quit it or kill command from another script. The Java program outputs error messages if any to the console.

现在,我想开发基于ExpressJ的NodeJs Web应用程序.当用户单击链接(运行)时,单击处理程序将调用Ajax请求,这将导致后端NodeJs脚本运行该Java程序(如果尚未运行).另一个链接(停止)将使Ajax请求停止该Java程序.

Now I want to develop express based NodeJs web application. When the user clicks on a link (Run) , the click handler will invoke Ajax request which will cause the backend NodeJs script to run this Java program if it is not already running. Another link (Stop) will make Ajax request to stop this Java program.

这如何实现?用示例代码回答将是最有用的.

How this can be achieved? Answer with sample code will be most useful.

还有一个要求:如果此NodeJs Web应用程序终止,则由它启动的Java程序将继续运行,即它不依赖于NodeJs Web应用程序.

Also there is a requirement: if this NodeJs web application is terminated, the Java program that was started by it, keeps running i.e. it is not dependent on NodeJs web application.

推荐答案

您可以启动子进程,并在不需要时发送终止信号.

You can start a child process, and send a kill signal when you don't need it.

var spawn = require('child_process').spawn;
var child = spawn('java', ['params1', 'param2']);

要终止该应用程序或模拟 CTRL + C ,请发送信号:

To kill the application, or to simulate a CTRL+C, send a signal:

// control + c is an interrupt signal
child.kill('SIGINT');

// or send from the main process
process.kill(child.pid, 'SIGINT');

如果要分离运行应用程序,则可能应该将PID写入某处.要运行分离的应用程序,请按以下方式运行它:

If you're going to run the application detached, you should probably write the PID somewhere. To run the application detached, run it like this:

var fs = require('fs');
var out = fs.openSync('./out.log', 'a');
var err = fs.openSync('./out.log', 'a');

var child = spawn('java', [], {
  detached: true,
  stdio: [ 'ignore', out, err ]
});
child.unref();

这会产生一个子进程,其I/O流与父进程无关.

This spawns a child process whose I/O streams aren't associated with the parent process.

这篇关于如何从NodeJs调用Java程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆