Skip to content

Commit

Permalink
fs: avoid emitting error EBADF for double close
Browse files Browse the repository at this point in the history
Changed the logic in fs.ReadStream and fs.WriteStream so that
close always calls the prototype method rather than the internal
event listener.

Fixes: nodejs#2950
PR-URL: nodejs#11225
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Evan Lucas <evanlucas@me.com>
  • Loading branch information
mcollina authored and krydos committed Feb 25, 2017
1 parent a146861 commit 26db7f1
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 13 deletions.
25 changes: 12 additions & 13 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -1855,28 +1855,27 @@ ReadStream.prototype.destroy = function() {


ReadStream.prototype.close = function(cb) {
var self = this;
if (cb)
this.once('close', cb);

if (this.closed || typeof this.fd !== 'number') {
if (typeof this.fd !== 'number') {
this.once('open', close);
this.once('open', this.close.bind(this, null));
return;
}
return process.nextTick(() => this.emit('close'));
}

this.closed = true;
close();

function close(fd) {
fs.close(fd || self.fd, function(er) {
if (er)
self.emit('error', er);
else
self.emit('close');
});
self.fd = null;
}

fs.close(this.fd, (er) => {
if (er)
this.emit('error', er);
else
this.emit('close');
});

this.fd = null;
};


Expand Down
11 changes: 11 additions & 0 deletions test/parallel/test-fs-read-stream-double-close.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict';

const common = require('../common');
const fs = require('fs');

const s = fs.createReadStream(__filename);

s.close(common.mustCall(noop));
s.close(common.mustCall(noop));

function noop() {}
14 changes: 14 additions & 0 deletions test/parallel/test-fs-write-stream-double-close.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

const common = require('../common');
const fs = require('fs');
const path = require('path');

common.refreshTmpDir();

const s = fs.createWriteStream(path.join(common.tmpDir, 'rw'));

s.close(common.mustCall(noop));
s.close(common.mustCall(noop));

function noop() {}

0 comments on commit 26db7f1

Please sign in to comment.