Skip to content
Browse files

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.
  • Loading branch information...
1 parent d5a5ae3 commit 571f2cd01ab47429c8798c98e8ee95c05c1a272c @bnoordhuis committed
Showing with 17 additions and 20 deletions.
  1. +6 −4 lib/fs.js
  2. +11 −16 test/simple/test-fs-write-stream-end.js
View
10 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
View
27 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();
+ stream.on('close', common.mustCall(function() { }));
+})();
+(function() {
+ var file = path.join(common.tmpDir, 'write-end-test1.txt');
+ var stream = fs.createWriteStream(file);
stream.end('a\n', 'utf8');
- stream.on('close', function() {
+ stream.on('close', common.mustCall(function() {
var content = fs.readFileSync(file, 'utf8');
assert.equal(content, 'a\n');
- writeEndOk = true;
- });
-
+ }));
})();
-
-
-process.on('exit', function() {
- assert.ok(writeEndOk);
-});
-

0 comments on commit 571f2cd

Please sign in to comment.
Something went wrong with that request. Please try again.