• 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 uncork() in the same tick.
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  // Default encoding given none was specified.
23  assert.strictEqual(encoding, 'buffer');
24
25  seenChunks.push(chunk);
26  cb();
27};
28// Let's record the stream end event.
29w.on('finish', () => {
30  seenEnd = true;
31});
32
33function writeChunks(remainingChunks, callback) {
34  const writeChunk = remainingChunks.shift();
35  let writeState;
36
37  if (writeChunk) {
38    setImmediate(() => {
39      writeState = w.write(writeChunk);
40      // We were not told to stop writing.
41      assert.ok(writeState);
42
43      writeChunks(remainingChunks, callback);
44    });
45  } else {
46    callback();
47  }
48}
49
50// Do an initial write.
51w.write('stuff');
52// The write was immediate.
53assert.strictEqual(seenChunks.length, 1);
54// Reset the chunks seen so far.
55seenChunks = [];
56
57// Trigger stream buffering.
58w.cork();
59
60// Write the bufferedChunks.
61writeChunks(inputChunks, () => {
62  // Should not have seen anything yet.
63  assert.strictEqual(seenChunks.length, 0);
64
65  // Trigger writing out the buffer.
66  w.uncork();
67
68  // Buffered bytes should be seen in current tick.
69  assert.strictEqual(seenChunks.length, 4);
70
71  // Did the chunks match.
72  for (let i = 0, l = expectedChunks.length; i < l; i++) {
73    const seen = seenChunks[i];
74    // There was a chunk.
75    assert.ok(seen);
76
77    const expected = Buffer.from(expectedChunks[i]);
78    // It was what we expected.
79    assert.ok(seen.equals(expected));
80  }
81
82  setImmediate(() => {
83    // The stream should not have been ended.
84    assert.ok(!seenEnd);
85  });
86});
87