1// Flags: --expose-internals 2'use strict'; 3 4const common = require('../common'); 5const assert = require('assert'); 6const fs = require('fs'); 7const path = require('path'); 8const SyncWriteStream = require('internal/fs/sync_write_stream'); 9 10const tmpdir = require('../common/tmpdir'); 11tmpdir.refresh(); 12 13const filename = path.join(tmpdir.path, 'sync-write-stream.txt'); 14 15// Verify constructing the instance with default options. 16{ 17 const stream = new SyncWriteStream(1); 18 19 assert.strictEqual(stream.fd, 1); 20 assert.strictEqual(stream.readable, false); 21 assert.strictEqual(stream.autoClose, true); 22} 23 24// Verify constructing the instance with specified options. 25{ 26 const stream = new SyncWriteStream(1, { autoClose: false }); 27 28 assert.strictEqual(stream.fd, 1); 29 assert.strictEqual(stream.readable, false); 30 assert.strictEqual(stream.autoClose, false); 31} 32 33// Verify that the file will be written synchronously. 34{ 35 const fd = fs.openSync(filename, 'w'); 36 const stream = new SyncWriteStream(fd); 37 const chunk = Buffer.from('foo'); 38 39 let calledSynchronously = false; 40 stream._write(chunk, null, common.mustCall(() => { 41 calledSynchronously = true; 42 }, 1)); 43 44 assert.ok(calledSynchronously); 45 assert.strictEqual(fs.readFileSync(filename).equals(chunk), true); 46 47 fs.closeSync(fd); 48} 49 50// Verify that the stream will unset the fd after destroy(). 51{ 52 const fd = fs.openSync(filename, 'w'); 53 const stream = new SyncWriteStream(fd); 54 55 stream.on('close', common.mustCall()); 56 assert.strictEqual(stream.destroy(), stream); 57 assert.strictEqual(stream.fd, null); 58} 59 60// Verify that the stream will unset the fd after destroySoon(). 61{ 62 const fd = fs.openSync(filename, 'w'); 63 const stream = new SyncWriteStream(fd); 64 65 stream.on('close', common.mustCall()); 66 assert.strictEqual(stream.destroySoon(), stream); 67 assert.strictEqual(stream.fd, null); 68} 69 70// Verify that calling end() will also destroy the stream. 71{ 72 const fd = fs.openSync(filename, 'w'); 73 const stream = new SyncWriteStream(fd); 74 75 assert.strictEqual(stream.fd, fd); 76 77 stream.end(); 78 stream.on('close', common.mustCall(() => { 79 assert.strictEqual(stream.fd, null); 80 })); 81} 82 83// Verify that an error on _write() triggers an 'error' event. 84{ 85 const fd = fs.openSync(filename, 'w'); 86 const stream = new SyncWriteStream(fd); 87 88 assert.strictEqual(stream.fd, fd); 89 stream._write({}, null, common.mustCall((err) => { 90 assert(err); 91 fs.closeSync(fd); 92 })); 93} 94