summaryrefslogtreecommitdiff
path: root/test/parallel/test-stream-promises.js
blob: 33bfa292720da18d59c34e0b187a427cf111415c (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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
'use strict';

const common = require('../common');
const stream = require('stream');
const {
  Readable,
  Writable,
  promises,
} = stream;
const {
  finished,
  pipeline,
} = require('stream/promises');
const fs = require('fs');
const assert = require('assert');
const { promisify } = require('util');

assert.strictEqual(promises.pipeline, pipeline);
assert.strictEqual(promises.finished, finished);
assert.strictEqual(pipeline, promisify(stream.pipeline));
assert.strictEqual(finished, promisify(stream.finished));

// pipeline success
{
  let finished = false;
  const processed = [];
  const expected = [
    Buffer.from('a'),
    Buffer.from('b'),
    Buffer.from('c'),
  ];

  const read = new Readable({
    read() { }
  });

  const write = new Writable({
    write(data, enc, cb) {
      processed.push(data);
      cb();
    }
  });

  write.on('finish', () => {
    finished = true;
  });

  for (let i = 0; i < expected.length; i++) {
    read.push(expected[i]);
  }
  read.push(null);

  pipeline(read, write).then(common.mustCall((value) => {
    assert.ok(finished);
    assert.deepStrictEqual(processed, expected);
  }));
}

// pipeline error
{
  const read = new Readable({
    read() { }
  });

  const write = new Writable({
    write(data, enc, cb) {
      cb();
    }
  });

  read.push('data');
  setImmediate(() => read.destroy());

  pipeline(read, write).catch(common.mustCall((err) => {
    assert.ok(err, 'should have an error');
  }));
}

// finished success
{
  async function run() {
    const rs = fs.createReadStream(__filename);

    let ended = false;
    rs.resume();
    rs.on('end', () => {
      ended = true;
    });
    await finished(rs);
    assert(ended);
  }

  run().then(common.mustCall());
}

// finished error
{
  const rs = fs.createReadStream('file-does-not-exist');

  assert.rejects(finished(rs), {
    code: 'ENOENT'
  }).then(common.mustCall());
}