Just call .end
on the process.stdin
stream
To me, this is a more straightforward (and documented) way of ending the stream.
console.log('Press Enter to allow process to terminate');
process.stdin.once('data', callback);
function callback (data) {
console.log('Process can terminate now');
process.stdin.end();
}
It's also worth noting that node sets the stream as the context for the callback function, so you can just call this.end
console.log('Press Enter to allow process to terminate');
process.stdin.once('data', callback);
function callback (data) {
// `this` refers to process.stdin here
console.log('Process can terminate now');
this.end();
}
You could also emit an end
event which has additional benefits like being able to call a function when the stream is finished.
console.log('Press Enter to allow process to terminate');
process.stdin.once('data', function(data) {
console.log('Process can terminate now');
this.emit("end");
});
process.stdin.on('end', function() {
console.log("all done now");
});
This would output
Press Enter to allow process to terminate
Process can terminate now
all done now
A final solution would be to use process.exit
. This allows you to terminate a program whenver you want.
for (var i=0; i<10; i++) {
process.stdout.write( i.toString() );
if (i > 3) process.exit();
}
Output
01234
This would work inside of a stream callback, as part of a child process, or any other bit of code.
process.stdin.once('data', function (d) { console.log('logged'); this.unref(); process.stdin.once('data', function (d2) { console.log('never logged') }) })
. This logs "logged", then waits for me to press Enter. When I press Enter, the process terminates. – Sensuous