fs: fix immediate WriteStream#end()

Fix an exception that was raised when the WriteStream was closed
immediately after creating it:

  TypeError: Cannot read property 'fd' of undefined
      at WriteStream.close (fs.js:1537:18)
      <snip>

Avoid the TypeError and make sure the file descriptor is closed.

Fixes #4745.
This commit is contained in:
Ben Noordhuis 2013-02-11 14:01:18 +01:00
parent ed3d553d82
commit c7b84a1d01
2 changed files with 20 additions and 23 deletions

View File

@ -1522,19 +1522,21 @@ ReadStream.prototype.destroy = function() {
ReadStream.prototype.close = function(cb) {
var self = this;
if (cb)
this.once('close', cb);
if (this.closed || 'number' !== typeof this.fd) {
if ('number' !== typeof this.fd)
if ('number' !== typeof this.fd) {
this.once('open', close);
return;
}
return process.nextTick(this.emit.bind(this, 'close'));
}
this.closed = true;
var self = this;
close();
function close() {
fs.close(self.fd, function(er) {
function close(fd) {
fs.close(fd || self.fd, function(er) {
if (er)
self.emit('error', er);
else

View File

@ -21,27 +21,22 @@
var common = require('../common');
var assert = require('assert');
var path = require('path');
var fs = require('fs');
var path = require('path'),
fs = require('fs');
var writeEndOk = false;
(function() {
debugger;
var file = path.join(common.tmpDir, 'write-end-test.txt');
var file = path.join(common.tmpDir, 'write-end-test0.txt');
var stream = fs.createWriteStream(file);
stream.end('a\n', 'utf8');
stream.on('close', function() {
var content = fs.readFileSync(file, 'utf8');
assert.equal(content, 'a\n');
writeEndOk = true;
});
stream.end();
stream.on('close', common.mustCall(function() { }));
})();
process.on('exit', function() {
assert.ok(writeEndOk);
});
(function() {
var file = path.join(common.tmpDir, 'write-end-test1.txt');
var stream = fs.createWriteStream(file);
stream.end('a\n', 'utf8');
stream.on('close', common.mustCall(function() {
var content = fs.readFileSync(file, 'utf8');
assert.equal(content, 'a\n');
}));
})();