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'; 23require('../common'); 24const assert = require('assert'); 25 26const path = require('path'); 27const fs = require('fs'); 28const tmpdir = require('../common/tmpdir'); 29const fn = path.join(tmpdir.path, 'write.txt'); 30tmpdir.refresh(); 31const file = fs.createWriteStream(fn, { 32 highWaterMark: 10 33}); 34 35const EXPECTED = '012345678910'; 36 37const callbacks = { 38 open: -1, 39 drain: -2, 40 close: -1 41}; 42 43file 44 .on('open', function(fd) { 45 console.error('open!'); 46 callbacks.open++; 47 assert.strictEqual(typeof fd, 'number'); 48 }) 49 .on('error', function(err) { 50 throw err; 51 }) 52 .on('drain', function() { 53 console.error('drain!', callbacks.drain); 54 callbacks.drain++; 55 if (callbacks.drain === -1) { 56 assert.strictEqual(fs.readFileSync(fn, 'utf8'), EXPECTED); 57 file.write(EXPECTED); 58 } else if (callbacks.drain === 0) { 59 assert.strictEqual(fs.readFileSync(fn, 'utf8'), EXPECTED + EXPECTED); 60 file.end(); 61 } 62 }) 63 .on('close', function() { 64 console.error('close!'); 65 assert.strictEqual(file.bytesWritten, EXPECTED.length * 2); 66 67 callbacks.close++; 68 assert.throws( 69 () => { 70 console.error('write after end should not be allowed'); 71 file.write('should not work anymore'); 72 }, 73 { 74 code: 'ERR_STREAM_WRITE_AFTER_END', 75 name: 'Error', 76 message: 'write after end' 77 } 78 ); 79 80 fs.unlinkSync(fn); 81 }); 82 83for (let i = 0; i < 11; i++) { 84 file.write(`${i}`); 85} 86 87process.on('exit', function() { 88 for (const k in callbacks) { 89 assert.strictEqual(callbacks[k], 0, `${k} count off by ${callbacks[k]}`); 90 } 91 console.log('ok'); 92}); 93