Receiving data via stdin and storing as a variable/array

你。 提交于 2019-11-28 02:25:07

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!