Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

javascript - Receiving data via stdin and storing as a variable/array

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...