Node.js child.stdin.write 无效

Node.js child.stdin.write doesn't work

当我尝试 运行 子进程并将一些文本放入标准输入时,它会抛出错误。 这是子进程的代码:

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 will return null thus you will get a NullPointerException if you tried to use Console.readLine. To fix, this use 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);
            }
        }

    }
}

参见: