Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to receive data via stdin which I have working:

const fs = require('fs');
const readStream = process.stdin;

readStream.pause();
readStream.setEncoding('utf8');

readStream.on('data', (data) => {
  console.log(data);
  });
readStream.resume();

Now what I need to do is store it as a variable so I can do some calculations before I return it via stdout.

Every time I try to so anything with it, like push certain data to an array it repeats the data until the stdin has finished, and I cant access it after it has finished. I cant find any resources online to help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
92 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use ReadableStream to process asynchronous tasks. Call .getReader() of ReadableStream instance to get an object which has a .read() method which when called returns an object having value and done properties. The controller passed to the constructor can queue tasks to be performed, the call to read() reads the enqueued data and sets the data at value property.

let n = 0;
let letters = "abcdefghijklmnopqrstuvwxyz";
const results = [];

let readableStream = new ReadableStream({
  pull(controller) {
    if (n < letters.length) controller.enqueue(letters[n++])
    else controller.close();
  }
});

let reader = readableStream.getReader();

let processStream = ({value, done}) => {
  if (done) return reader.closed.then(() => results);
  console.log(value);
  // do stuff
  let next = new Promise(resolve => 
    setTimeout(() => {results.push(value); resolve()}
    , Math.floor(Math.random() * 1200))
  );
  return next.then(() => reader.read())
         .then(data => processStream(data));
}

reader.read()
.then(data => processStream(data))
.then(res => console.log(res));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...