1'use strict';
2
3const common = require('../common');
4const fs = require('fs');
5const assert = require('assert');
6
7const debuglog = (arg) => {
8  console.log(new Date().toLocaleString(), arg);
9};
10
11const tmpdir = require('../common/tmpdir');
12tmpdir.refresh();
13
14{
15  // Compat error.
16  debuglog('start test');
17
18  function WriteStream(...args) {
19    debuglog('WriteStream constructor');
20    fs.WriteStream.call(this, ...args);
21  }
22  Object.setPrototypeOf(WriteStream.prototype, fs.WriteStream.prototype);
23  Object.setPrototypeOf(WriteStream, fs.WriteStream);
24
25  WriteStream.prototype.open = common.mustCall(function WriteStream$open() {
26    debuglog('WriteStream open() callback');
27    const that = this;
28    fs.open(that.path, that.flags, that.mode, (err, fd) => {
29      debuglog('inner fs open() callback');
30      that.emit('error', err);
31    });
32  });
33
34  fs.open(`${tmpdir.path}/dummy`, 'wx+', common.mustCall((err, fd) => {
35    debuglog('fs open() callback');
36    assert.ifError(err);
37    fs.close(fd, () => { debuglog(`closed ${fd}`); });
38    const w = new WriteStream(`${tmpdir.path}/dummy`,
39                              { flags: 'wx+', emitClose: true })
40      .on('error', common.mustCall((err) => {
41        debuglog('error event callback');
42        assert.strictEqual(err.code, 'EEXIST');
43        w.destroy();
44        w.on('close', common.mustCall(() => {
45          debuglog('close event callback');
46        }));
47      }));
48  }));
49  debuglog('waiting for callbacks');
50}
51