How to emit/pipe array values as a readable stream in node.js?

前端 未结 5 2218
梦谈多话
梦谈多话 2021-02-07 09:23

What is the best way to create a readable stream from an array and pipe values to a writable stream? I have seen substack\'s example using setInterval and I can implement that s

5条回答
  •  遥遥无期
    2021-02-07 10:19

    tl;dr;

    This is a LIFO solution. Array.prototype.pop() has similar behavior to shift but applied to the last element in an array.

    const items = [1,2,3]
    const stream = new Readable({
      objectMode: true,
      read() {
        const item = items.pop()
        if (!item) {
          this.push(null);
          return;
        }
        this.push(item)
      },
    })
    

提交回复
热议问题