summaryrefslogtreecommitdiff
path: root/test/parallel/test-stream-readable-pause-and-resume.js
blob: 4d7d860a6373d4b45c4cfbba218f0157e4dfb690 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
'use strict';

const common = require('../common');
const { Readable } = require('stream');

let ticks = 18;
let expectedData = 19;

const rs = new Readable({
  objectMode: true,
  read: () => {
    if (ticks-- > 0)
      return process.nextTick(() => rs.push({}));
    rs.push({});
    rs.push(null);
  }
});

rs.on('end', common.mustCall());
readAndPause();

function readAndPause() {
  // Does a on(data) -> pause -> wait -> resume -> on(data) ... loop.
  // Expects on(data) to never fire if the stream is paused.
  const ondata = common.mustCall((data) => {
    rs.pause();

    expectedData--;
    if (expectedData <= 0)
      return;

    setImmediate(function() {
      rs.removeListener('data', ondata);
      readAndPause();
      rs.resume();
    });
  }, 1); // Only call ondata once

  rs.on('data', ondata);
}