From f5e40470643d8cc97ad4aa85fbca4b2805cc0481 Mon Sep 17 00:00:00 2001 From: Tobie Langel Date: Wed, 8 Sep 2010 13:19:25 +0200 Subject: [PATCH] Avoid closing a WriteStream before it has been opened. --- lib/fs.js | 27 +++++++++++++++------------ test/simple/test-fs-write-stream.js | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+), 12 deletions(-) create mode 100644 test/simple/test-fs-write-stream.js diff --git a/lib/fs.js b/lib/fs.js index d2293e66a2..74c56f64df 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -949,20 +949,23 @@ WriteStream.prototype.destroy = function (cb) { var self = this; this.writeable = false; - fs.close(self.fd, function(err) { - if (err) { - if (cb) { - cb(err); + function close() { + fs.close(self.fd, function(err) { + if (err) { + if (cb) { cb(err); } + self.emit('error', err); + return; } - self.emit('error', err); - return; - } + if (cb) { cb(null); } + self.emit('close'); + }); + } - if (cb) { - cb(null); - } - self.emit('close'); - }); + if (this.fd) { + close(); + } else { + this.addListener('open', close); + } }; diff --git a/test/simple/test-fs-write-stream.js b/test/simple/test-fs-write-stream.js new file mode 100644 index 0000000000..541d819229 --- /dev/null +++ b/test/simple/test-fs-write-stream.js @@ -0,0 +1,19 @@ +common = require("../common"); +assert = common.assert + +var path = require('path'), + fs = require('fs'); + +var file = path.join(common.fixturesDir, "write.txt"); + +(function() { + var stream = fs.createWriteStream(file), + _fs_close = fs.close; + + fs.close = function(fd) { + assert.ok(fd, "fs.close must not be called without an undefined fd.") + fs.close = _fs_close; + } + stream.destroy(); +})(); +