Receiving data via stdin and storing as a variable

2019-01-29 11:50发布

问题:

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.

回答1:

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

You can also pipe the ReadableStream and .pipeTo() method of the instance to pipe the enqueued data to a WritableStream instance, where tasks can be performed at both read and write portions of the stream.

const letters = "abcdefghijklmnopqrstuvwxyz";

let RSController = class {
  constructor(input) {
    this.input = input;
    this.n = 0;
  }
  async pull(controller) {
    if (this.n < this.input.length) {
      let curr = await this.handleData(this.input[this.n]);
      ++this.n;
      controller.enqueue(curr);
    } else {
      this.n = 0;
      controller.close();
    }
  }
  cancel(err) {
    console.log(err)
  }
  handleData(data) {
    return new Promise(resolve => {
      // do stuff
      setTimeout(() => {
        resolve(data)
      }, Math.floor(Math.random() * 750))
    })
  }
}

let WSController = class {
  constructor(arr = []) {
    this.results = arr;
  }
  write(data) {
    let dataUp = data.toUpperCase();
    console.log(data, dataUp);
    this.results.push([data, dataUp]);
  }
  close() {
    console.log(JSON.stringify(this.results, null, 2));
  }
  abort(e) {
    console.error(e);
  }
}

let rscontroller = new RSController(letters);

let readableStream = new ReadableStream(rscontroller);

let wscontroller = new WSController([]);

let writableStream = new WritableStream(wscontroller);

readableStream
.pipeTo(writableStream);