inthenameofmusik
inthenameofmusik

Reputation: 623

Node Js process.stdin

I'm just now getting into node.js and reading input from the command line.

I'm a bit confused on the following code example.

process.stdin.setEncoding('utf8');

process.stdin.on('readable', () => {
  var chunk = process.stdin.read();
  if (chunk !== null) {
    process.stdout.write(`data: ${chunk}`);
  }
});

process.stdin.on('end', () => {
  process.stdout.write('end');
});

First, in old mode, process.stdin.resume() was needed to make it begin to listen. Doesn't using resume() make more sense for performance? Doesn't this continually listen, using up processing power that it doesn't need to use up?

Also, I read the docs but I'm not understanding what 'end' does here.

The docs say:

This event fires when there will be no more data to read.

But 'readable' is always listening so we never get to the 'end'?

Upvotes: 0

Views: 3060

Answers (1)

zoubida13
zoubida13

Reputation: 1759

Continually listening for input doesn't necessarily use more resources than resuming the stream manually. It's just a different way of handling the pipes.

The "readable" part stops listening when the "end" event is triggered, as end will close the stream and therefore there won't be anything readable anymore.

The end event is a translation of the end signal fired to the standard input (for instance a CTRL/D on a unix system.

Upvotes: 2

Related Questions