• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright Joyent, Inc. and other Node contributors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21 
22 'use strict';
23 const common = require('../common');
24 const assert = require('assert');
25 
26 const path = require('path');
27 const fs = require('fs');
28 const tmpdir = require('../common/tmpdir');
29 const fn = path.join(tmpdir.path, 'write.txt');
30 tmpdir.refresh();
31 const file = fs.createWriteStream(fn, {
32   highWaterMark: 10
33 });
34 
35 const EXPECTED = '012345678910';
36 
37 const callbacks = {
38   open: -1,
39   drain: -2,
40   close: -1
41 };
42 
43 file
44   .on('open', function(fd) {
45     console.error('open!');
46     callbacks.open++;
47     assert.strictEqual(typeof fd, 'number');
48   })
49   .on('drain', function() {
50     console.error('drain!', callbacks.drain);
51     callbacks.drain++;
52     if (callbacks.drain === -1) {
53       assert.strictEqual(fs.readFileSync(fn, 'utf8'), EXPECTED);
54       file.write(EXPECTED);
55     } else if (callbacks.drain === 0) {
56       assert.strictEqual(fs.readFileSync(fn, 'utf8'), EXPECTED + EXPECTED);
57       file.end();
58     }
59   })
60   .on('close', function() {
61     console.error('close!');
62     assert.strictEqual(file.bytesWritten, EXPECTED.length * 2);
63 
64     callbacks.close++;
65     console.error('write after end should not be allowed');
66     file.write('should not work anymore', common.expectsError({
67       code: 'ERR_STREAM_WRITE_AFTER_END',
68       name: 'Error',
69       message: 'write after end'
70     }));
71 
72     fs.unlinkSync(fn);
73   });
74 
75 for (let i = 0; i < 11; i++) {
76   file.write(`${i}`);
77 }
78 
79 process.on('exit', function() {
80   for (const k in callbacks) {
81     assert.strictEqual(callbacks[k], 0, `${k} count off by ${callbacks[k]}`);
82   }
83   console.log('ok');
84 });
85