|
| 1 | +// Flags: --expose-internals |
| 2 | +'use strict'; |
| 3 | + |
| 4 | +const common = require('../common'); |
| 5 | +const assert = require('assert'); |
| 6 | +const fs = require('fs'); |
| 7 | +const path = require('path'); |
| 8 | +const SyncWriteStream = require('internal/fs').SyncWriteStream; |
| 9 | + |
| 10 | +common.refreshTmpDir(); |
| 11 | + |
| 12 | +const filename = path.join(common.tmpDir, 'sync-write-stream.txt'); |
| 13 | + |
| 14 | +// Verify constructing the instance with defualt options. |
| 15 | +{ |
| 16 | + const stream = new SyncWriteStream(1); |
| 17 | + |
| 18 | + assert.strictEqual(stream.fd, 1); |
| 19 | + assert.strictEqual(stream.readable, false); |
| 20 | + assert.strictEqual(stream.autoClose, true); |
| 21 | + assert.strictEqual(stream.listenerCount('end'), 1); |
| 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 | + assert.strictEqual(stream.listenerCount('end'), 1); |
| 32 | +} |
| 33 | + |
| 34 | +// Verfiy that the file will be writen synchronously. |
| 35 | +{ |
| 36 | + const fd = fs.openSync(filename, 'w'); |
| 37 | + const stream = new SyncWriteStream(fd); |
| 38 | + const chunk = Buffer.from('foo'); |
| 39 | + |
| 40 | + assert.strictEqual(stream._write(chunk, null, common.mustCall(1)), true); |
| 41 | + assert.strictEqual(fs.readFileSync(filename).equals(chunk), true); |
| 42 | +} |
| 43 | + |
| 44 | +// Verify that the stream will unset the fd after destory(). |
| 45 | +{ |
| 46 | + const fd = fs.openSync(filename, 'w'); |
| 47 | + const stream = new SyncWriteStream(fd); |
| 48 | + |
| 49 | + stream.on('close', common.mustCall(3)); |
| 50 | + |
| 51 | + assert.strictEqual(stream.destroy(), true); |
| 52 | + assert.strictEqual(stream.fd, null); |
| 53 | + assert.strictEqual(stream.destroy(), true); |
| 54 | + assert.strictEqual(stream.destroySoon(), true); |
| 55 | +} |
| 56 | + |
| 57 | +// Verfit that the 'end' event listener will also destroy the stream. |
| 58 | +{ |
| 59 | + const fd = fs.openSync(filename, 'w'); |
| 60 | + const stream = new SyncWriteStream(fd); |
| 61 | + |
| 62 | + assert.strictEqual(stream.fd, fd); |
| 63 | + |
| 64 | + stream.emit('end'); |
| 65 | + assert.strictEqual(stream.fd, null); |
| 66 | +} |
0 commit comments