简体   繁体   中英

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' ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM