Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS: Send EOF to stdin stream without closing stream

How can I signal EOF to a stream without closing the stream?

I've got a script that waits for input on stdin, then when I push ctrl-d, it spits output to stdout, then waits again for stdin until I press ctrl-d.

In my nodejs script, I want to spawn that script, write to the stdin stream, then somehow signal EOF without closing the stream. This doesn't work:

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

But if I change child.stdin.write(...) to child.stdin.end(...), it works, but only once; the stream is closed after that. I read somewhere that EOF isn't actually a character, it's just anything that's NOT a character, usually -1, so I tried this, but this didn't work either:

var EOF = new Buffer(1); EOF[0] = -1;
child.stdin.write("hello child\n");
child.stdin.write(EOF);
like image 457
Trevor Dixon Avatar asked Jun 01 '12 00:06

Trevor Dixon


2 Answers

Have you tried child.stdin.write("\x04");? This is the ascii code for Ctrl+D.

like image 142
cjohn Avatar answered Nov 19 '22 16:11

cjohn


You did it with res just two lines below...

  • stream.write(data) is used when you, want to continue writing
  • stream.end([data]) is used when you don't need to send more data (it will close the stream)
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');
like image 3
Kevin Sandow Avatar answered Nov 19 '22 16:11

Kevin Sandow