• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../common');
3const assert = require('assert');
4
5const { Readable, Writable } = require('stream');
6
7const ABC = new Uint8Array([0x41, 0x42, 0x43]);
8const DEF = new Uint8Array([0x44, 0x45, 0x46]);
9const GHI = new Uint8Array([0x47, 0x48, 0x49]);
10
11{
12  // Simple Writable test.
13
14  let n = 0;
15  const writable = new Writable({
16    write: common.mustCall((chunk, encoding, cb) => {
17      assert(chunk instanceof Buffer);
18      if (n++ === 0) {
19        assert.strictEqual(String(chunk), 'ABC');
20      } else {
21        assert.strictEqual(String(chunk), 'DEF');
22      }
23
24      cb();
25    }, 2)
26  });
27
28  writable.write(ABC);
29  writable.end(DEF);
30}
31
32{
33  // Writable test, pass in Uint8Array in object mode.
34
35  const writable = new Writable({
36    objectMode: true,
37    write: common.mustCall((chunk, encoding, cb) => {
38      assert(!(chunk instanceof Buffer));
39      assert(chunk instanceof Uint8Array);
40      assert.strictEqual(chunk, ABC);
41      assert.strictEqual(encoding, 'utf8');
42      cb();
43    })
44  });
45
46  writable.end(ABC);
47}
48
49{
50  // Writable test, multiple writes carried out via writev.
51  let callback;
52
53  const writable = new Writable({
54    write: common.mustCall((chunk, encoding, cb) => {
55      assert(chunk instanceof Buffer);
56      assert.strictEqual(encoding, 'buffer');
57      assert.strictEqual(String(chunk), 'ABC');
58      callback = cb;
59    }),
60    writev: common.mustCall((chunks, cb) => {
61      assert.strictEqual(chunks.length, 2);
62      assert.strictEqual(chunks[0].encoding, 'buffer');
63      assert.strictEqual(chunks[1].encoding, 'buffer');
64      assert.strictEqual(chunks[0].chunk + chunks[1].chunk, 'DEFGHI');
65    })
66  });
67
68  writable.write(ABC);
69  writable.write(DEF);
70  writable.end(GHI);
71  callback();
72}
73
74{
75  // Simple Readable test.
76  const readable = new Readable({
77    read() {}
78  });
79
80  readable.push(DEF);
81  readable.unshift(ABC);
82
83  const buf = readable.read();
84  assert(buf instanceof Buffer);
85  assert.deepStrictEqual([...buf], [...ABC, ...DEF]);
86}
87
88{
89  // Readable test, setEncoding.
90  const readable = new Readable({
91    read() {}
92  });
93
94  readable.setEncoding('utf8');
95
96  readable.push(DEF);
97  readable.unshift(ABC);
98
99  const out = readable.read();
100  assert.strictEqual(out, 'ABCDEF');
101}
102