下面是一个可读流的简单例子,依次触发读取 1 到 1,000,000:

    1. const { Readable } = require('stream');
    2. class Counter extends Readable {
    3. constructor(opt) {
    4. super(opt);
    5. this._max = 1000000;
    6. this._index = 1;
    7. }
    8. _read() {
    9. const i = this._index++;
    10. if (i > this._max)
    11. this.push(null);
    12. else {
    13. const str = String(i);
    14. const buf = Buffer.from(str, 'ascii');
    15. this.push(buf);
    16. }
    17. }
    18. }