• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2require('../common');
3const assert = require('assert');
4const stream = require('stream');
5const Writable = stream.Writable;
6
7// Test the buffering behavior of Writable streams.
8//
9// The call to cork() triggers storing chunks which are flushed
10// on calling end() and the stream subsequently ended.
11//
12// node version target: 0.12
13
14const expectedChunks = ['please', 'buffer', 'me', 'kindly'];
15const inputChunks = expectedChunks.slice(0);
16let seenChunks = [];
17let seenEnd = false;
18
19const w = new Writable();
20// Let's arrange to store the chunks.
21w._write = function(chunk, encoding, cb) {
22  // Stream end event is not seen before the last write.
23  assert.ok(!seenEnd);
24  // Default encoding given none was specified.
25  assert.strictEqual(encoding, 'buffer');
26
27  seenChunks.push(chunk);
28  cb();
29};
30// Let's record the stream end event.
31w.on('finish', () => {
32  seenEnd = true;
33});
34
35function writeChunks(remainingChunks, callback) {
36  const writeChunk = remainingChunks.shift();
37  let writeState;
38
39  if (writeChunk) {
40    setImmediate(() => {
41      writeState = w.write(writeChunk);
42      // We were not told to stop writing.
43      assert.ok(writeState);
44
45      writeChunks(remainingChunks, callback);
46    });
47  } else {
48    callback();
49  }
50}
51
52// Do an initial write.
53w.write('stuff');
54// The write was immediate.
55assert.strictEqual(seenChunks.length, 1);
56// Reset the seen chunks.
57seenChunks = [];
58
59// Trigger stream buffering.
60w.cork();
61
62// Write the bufferedChunks.
63writeChunks(inputChunks, () => {
64  // Should not have seen anything yet.
65  assert.strictEqual(seenChunks.length, 0);
66
67  // Trigger flush and ending the stream.
68  w.end();
69
70  // Stream should not ended in current tick.
71  assert.ok(!seenEnd);
72
73  // Buffered bytes should be seen in current tick.
74  assert.strictEqual(seenChunks.length, 4);
75
76  // Did the chunks match.
77  for (let i = 0, l = expectedChunks.length; i < l; i++) {
78    const seen = seenChunks[i];
79    // There was a chunk.
80    assert.ok(seen);
81
82    const expected = Buffer.from(expectedChunks[i]);
83    // It was what we expected.
84    assert.ok(seen.equals(expected));
85  }
86
87  setImmediate(() => {
88    // Stream should have ended in next tick.
89    assert.ok(seenEnd);
90  });
91});
92