当我尝试运行子进程并向其输入一些文本时,它会抛出错误。 这是子进程的代码:
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);
}
}
}
运行此过程的脚本代码:
var spawn = require('child_process').spawn;
var child = spawn('java', ['HelloWorld', 'HelloWorld.class']);
child.stdin.setEncoding('utf-8');
child.stdout.pipe(process.stdout);
child.stdin.write("tratata\n");
// child.stdin.end();
它抛出:
events.js:161
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at exports._errnoException (util.js:1028:11)
at Pipe.onread (net.js:572:26)
注意,当我用 child.stdin.end(); 取消注释行时没有任何反应就结束了
最佳答案
要使脚本正常工作,您需要做的一件事就是添加:
process.stdin.pipe(child.stdin);
如果您在 child.stdin.write
之前添加此内容,则可以解决一半问题。另一半与 Java 方面有关。如果 java 程序不是通过键入 java HelloWorld
从控制台启动的,则 Console
将返回 null 因此你将得到 NullPointerException
如果您尝试使用 Console.readLine
。要修复此问题,请使用 BufferedReader
相反。
将脚本更改为:
const spawn = require('child_process').spawn;
const child = spawn('java', ['HelloWorld'], {
stdio: ['pipe', process.stdout, process.stderr]
});
process.stdin.pipe(child.stdin);
setTimeout(() => {
child.stdin.write('tratata\n');
}, 1000);
然后将你的java代码更改为:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class HelloWorld {
public static void main(String[] args) throws IOException {
System.out.println("started");
try(BufferedReader console = new BufferedReader(new InputStreamReader(System.in))) {
for (String line = console.readLine(); line != null; line = console.readLine()) {
System.out.printf("Your sentence: %s\n", line);
}
}
}
}
参见:
关于javascript - Node.js child.stdin.write 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43236983/