如何从 NodeJs 调用 Java 程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18815734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call Java program from NodeJs
提问by rjc
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.
我有一个通常从命令行启动的 Java 程序。从命令行启动后,java 程序将一直运行,直到按下 Ctrl+C 退出它或从另一个脚本中终止命令。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.
现在我想开发基于 Express 的 NodeJs Web 应用程序。当用户单击链接 (Run) 时,单击处理程序将调用 Ajax 请求,这将导致后端 NodeJs 脚本运行该 Java 程序(如果它尚未运行)。另一个链接(停止)将发出 Ajax 请求以停止此 Java 程序。
How this can be achieved? Answer with sample code will be most useful.
如何做到这一点?使用示例代码回答将是最有用的。
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.
还有一个要求:如果这个 NodeJs web 应用程序被终止,由它启动的 Java 程序会继续运行,即它不依赖于 NodeJs web 应用程序。
采纳答案by hexacyanide
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']);
To kill the application, or to simulate a CTRL+C, send a signal:
要终止应用程序或模拟CTRL+ C,请发送信号:
// control + c is an interrupt signal
child.kill('SIGINT');
// or send from the main process
process.kill(child.pid, 'SIGINT');
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:
如果您要分离运行应用程序,您可能应该在某处写入 PID。要运行分离的应用程序,请像这样运行它:
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();
This spawns a child process whose I/O streams aren't associated with the parent process.
这会产生一个子进程,其 I/O 流与父进程无关。
回答by Peter Ulanga
Normally spawned child process would not end even when the parent process exits. To kill the child process, the child process pid need to be recorded somewhere (in a file to allow the value to exist even when the parent process exits) and the same can be used to kill the child process when required.
即使父进程退出,通常产生的子进程也不会结束。要杀死子进程,需要将子进程 pid 记录在某处(在文件中,即使在父进程退出时也允许该值存在),并且可以在需要时使用相同的方法杀死子进程。