javascript 如何从 node.js 调用 java 程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32039111/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:45:47  来源:igfitidea点击:

How to call a java program from node.js?

javascriptjavanode.js

提问by sneaky

I have a node.js script and a java program in the same folder (.class and .java and .js). I want to call the java program from the node.js script. In terminal I can call the java program like this

我在同一个文件夹(.class 和 .java 和 .js)中有一个 node.js 脚本和一个 java 程序。我想从 node.js 脚本中调用 java 程序。在终端我可以像这样调用java程序

java -cp java-json.jar:. PlutoMake "tests/android.png"

java -cp java-json.jar:. PlutoMake "tests/android.png"

I saw this thread How to call Java program from NodeJs

我看到了这个线程How to call Java program from NodeJs

and I am trying to do the same thing, here is the node.js code

我正在尝试做同样的事情,这是 node.js 代码

var child = spawn('java', ['-cp java-json.jar:. PlutoMake', 'tests/android.png']);

This seems to run without crashing, but then nothing happens. The java program creates an image, but if I do it through node, it doesn't work. Does anyone know whats wrong?

这似乎运行没有崩溃,但随后什么也没有发生。java程序创建了一个图像,但是如果我通过node来做,它就不起作用了。有谁知道出了什么问题?

Thanks

谢谢

回答by Ry-

The array of arguments you pass should have one element per argument. You're incorrectly combining a few of them.

您传递的参数数组每个参数应该有一个元素。您错误地组合了其中的一些。

var child = spawn('java', ['-cp', 'java-json.jar:.', 'PlutoMake', 'tests/android.png']);

Checking the output and exit code could prove useful:

检查输出和退出代码可能很有用:

child.on('close', function (exitCode) {
    if (exitCode !== 0) {
        console.error('Something went wrong!');
    }
});

// If you're really just passing it through, though, pass {stdio: 'inherit'}
// to child_process.spawn instead.
child.stderr.on('data', function (data) {
    process.stderr.write(data);
});