From c7b84a1d01fa4fd6ccff1ceb917a5aaf59694244 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Mon, 11 Feb 2013 14:01:18 +0100 Subject: [PATCH] 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) Avoid the TypeError and make sure the file descriptor is closed. Fixes #4745. --- lib/fs.js | 10 +++++--- test/simple/test-fs-write-stream-end.js | 33 +++++++++++-------------- 2 files changed, 20 insertions(+), 23 deletions(-) diff --git a/lib/fs.js b/lib/fs.js index 8be6cf85899..5cbc43b5e95 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -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 diff --git a/test/simple/test-fs-write-stream-end.js b/test/simple/test-fs-write-stream-end.js index 2a85ac3eea6..7bbc5d68e0e 100644 --- a/test/simple/test-fs-write-stream-end.js +++ b/test/simple/test-fs-write-stream-end.js @@ -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'); + })); +})();