Skip to content

Commit d65832c

Browse files
committed
fs: fix WriteStream fd leak
Close the file descriptor when a write operation fails. Fixes #4387.
1 parent 6e97b2c commit d65832c

File tree

2 files changed

+64
-3
lines changed

2 files changed

+64
-3
lines changed

lib/fs.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1493,10 +1493,19 @@ WriteStream.prototype.flush = function() {
14931493

14941494
if (err) {
14951495
self.writable = false;
1496-
if (cb) {
1497-
cb(err);
1496+
1497+
function emit() {
1498+
self.fd = null;
1499+
if (cb) cb(err);
1500+
self.emit('error', err);
14981501
}
1499-
self.emit('error', err);
1502+
1503+
if (self.fd === null) {
1504+
emit();
1505+
} else {
1506+
fs.close(self.fd, emit);
1507+
}
1508+
15001509
return;
15011510
}
15021511

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Copyright Joyent, Inc. and other Node contributors.
2+
//
3+
// Permission is hereby granted, free of charge, to any person obtaining a
4+
// copy of this software and associated documentation files (the
5+
// "Software"), to deal in the Software without restriction, including
6+
// without limitation the rights to use, copy, modify, merge, publish,
7+
// distribute, sublicense, and/or sell copies of the Software, and to permit
8+
// persons to whom the Software is furnished to do so, subject to the
9+
// following conditions:
10+
//
11+
// The above copyright notice and this permission notice shall be included
12+
// in all copies or substantial portions of the Software.
13+
//
14+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15+
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16+
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17+
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18+
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19+
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20+
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21+
22+
var common = require('../common');
23+
var assert = require('assert');
24+
var fs = require('fs');
25+
26+
var stream = fs.createWriteStream(common.tmpDir + '/out');
27+
var err = new Error('BAM');
28+
29+
stream.write(new Buffer(256), function() {
30+
var fd = stream.fd;
31+
32+
fs.write = function() {
33+
var cb = arguments[arguments.length - 1];
34+
process.nextTick(function() {
35+
cb(err);
36+
});
37+
};
38+
39+
fs.close = function(fd_, cb) {
40+
assert.equal(fd_, fd);
41+
process.nextTick(cb);
42+
};
43+
44+
stream.write(new Buffer(256), common.mustCall(function(err_) {
45+
assert.equal(err_, err);
46+
}));
47+
48+
stream.on('error', common.mustCall(function(err_) {
49+
assert.equal(stream.fd, null);
50+
assert.equal(err_, err);
51+
}));
52+
});

0 commit comments

Comments
 (0)