[英]How to use CLI application from node.js child process?
I am wordering how to use application with command line interface from node.js. 我在写文章如何使用来自node.js的命令行界面的应用程序。 Here is node.js code: 这是node.js代码:
var spawn = require('child_process').spawn;
var child = spawn('java', ['HelloWorld']);
child.stdout.pipe(process.stdout);
child.stdin.write("tratata\r\n;");
child.stdin.end();
it runs java HelloWorld cli app. 它运行Java HelloWorld CLI应用程序。
here is java code: 这是java代码:
import java.io.Console;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("started");
Console console = System.console();
while (true) {
String s = console.readLine();
System.out.println("Your sentence:" + s);
}
}
}
but it doesn't work. 但这不起作用。 when child.stdin.write
executs - nothing happening. 当child.stdin.write
执行时-没有任何反应。
Disclaimer: I know next to nothing about Java. 免责声明:我对Java几乎一无所知。
My guess is that java.io.Console
does a lot more than just reading from stdin, like opening the console device ( /dev/tty
on most Unix-like OS'es) itself, thereby circumventing the stdin/stdout/stderr
devices being passed in by Node. 我的猜测是java.io.Console
所做的不只是读取stdin的内容,例如本身打开控制台设备(在大多数类似Unix的OS中为/dev/tty
),从而规避了stdin/stdout/stderr
设备由Node传递。
If you use java.io.BufferedReader
, it works better: 如果使用java.io.BufferedReader
,则效果更好:
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("started");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
try {
String s = reader.readLine();
if (s == null) return; // end of stream reached
System.out.println("Your sentence:" + s);
} catch(IOException e) {
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.