Skip to content

Commit b1fc774

Browse files
committed
fs: avoid emitting error EBADF for double close
Changed the logic in fs.ReadStream and fs.WriteStream so that close always calls the prototype method rather than the internal event listener. Fixes: #2950 PR-URL: #11225 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Evan Lucas <[email protected]>
1 parent 6dd979e commit b1fc774

File tree

3 files changed

+37
-13
lines changed

3 files changed

+37
-13
lines changed

lib/fs.js

+12-13
Original file line numberDiff line numberDiff line change
@@ -1855,28 +1855,27 @@ ReadStream.prototype.destroy = function() {
18551855

18561856

18571857
ReadStream.prototype.close = function(cb) {
1858-
var self = this;
18591858
if (cb)
18601859
this.once('close', cb);
1860+
18611861
if (this.closed || typeof this.fd !== 'number') {
18621862
if (typeof this.fd !== 'number') {
1863-
this.once('open', close);
1863+
this.once('open', this.close.bind(this, null));
18641864
return;
18651865
}
18661866
return process.nextTick(() => this.emit('close'));
18671867
}
1868+
18681869
this.closed = true;
1869-
close();
1870-
1871-
function close(fd) {
1872-
fs.close(fd || self.fd, function(er) {
1873-
if (er)
1874-
self.emit('error', er);
1875-
else
1876-
self.emit('close');
1877-
});
1878-
self.fd = null;
1879-
}
1870+
1871+
fs.close(this.fd, (er) => {
1872+
if (er)
1873+
this.emit('error', er);
1874+
else
1875+
this.emit('close');
1876+
});
1877+
1878+
this.fd = null;
18801879
};
18811880

18821881

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const fs = require('fs');
5+
6+
const s = fs.createReadStream(__filename);
7+
8+
s.close(common.mustCall(noop));
9+
s.close(common.mustCall(noop));
10+
11+
function noop() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const fs = require('fs');
5+
const path = require('path');
6+
7+
common.refreshTmpDir();
8+
9+
const s = fs.createWriteStream(path.join(common.tmpDir, 'rw'));
10+
11+
s.close(common.mustCall(noop));
12+
s.close(common.mustCall(noop));
13+
14+
function noop() {}

0 commit comments

Comments
 (0)