NodeJS:将EOF发送到stdin流而不关闭流

Tre*_*xon 15 javascript node.js

如何在不关闭流的情况下向流中发送EOF信号?

我有一个等待stdin输入的脚本,然后当我按下ctrl-d时,它会将输出吐出到stdout,然后再次等待stdin直到我按下ctrl-d.

在我的nodejs脚本中,我想生成该脚本,写入stdin流,然后以某种方式发出EOF信号而不关闭流.这不起作用:

var http = require('http'),
    spawn = require('child_process').spawn;

var child = spawn('my_child_process');
child.stdout.on('data', function(data) {
    console.log(data.toString());
});

child.stdout.on('close', function() {
    console.log('closed');
})

http.createServer(function (req, res) {
    child.stdin.write('hello child\n');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
Run Code Online (Sandbox Code Playgroud)

但是,如果我将child.stdin.write(...)更改为child.stdin.end(...),它可以工作,但只能执行一次; 之后关闭流.我在某处看到EOF实际上并不是一个角色,它只是一个不是一个角色的东西,通常为-1,所以我试过这个,但这也不起作用:

var EOF = new Buffer(1); EOF[0] = -1;
child.stdin.write("hello child\n");
child.stdin.write(EOF);
Run Code Online (Sandbox Code Playgroud)

cjo*_*ohn 5

你试过了child.stdin.write("\x04");吗?这是Ctrl + D的ASCII代码。