NodeJS:发送EOF到标准inputstream而不closuresstream

如何在不closuresstream的情况下将EOF发送到stream?

我有一个等待inputstdin的脚本,然后当我按ctrl-d,它吐出输出到标准输出,然后再次等待stdin,直到我按ctrl-d。

在我的nodejs脚本中,我想生成该脚本,写入stdinstream,然后以某种方式发信号EOF而不closuresstream。 这不起作用:

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'); 

但是,如果我将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); 

你有没有尝试过child.stdin.write("\x04"); ? 这是Ctrl + D的ASCII码。

你只用下面的两行就可以做到

  • 当你想使用stream.write(data)的时候,要继续写
  • stream.end([data])用于不需要发送更多数据(它将closuresstream)
 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.end('hello child\n'); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); 
 var os = require("os"); child.stdin.write("hello child\n"); child.stdin.write(os.EOL); 

我在我的项目中使用它,它的工作原理