Skip to content

Commit

Permalink
fs: inline only the required logic into fs.WriteStream#_write
Browse files Browse the repository at this point in the history
This avoids a number of type checks and a maybeCallback call that
was being done by fs.write before.
  • Loading branch information
ronkorving committed Oct 14, 2015
1 parent 6f14b3a commit 65b0241
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 15 deletions.
29 changes: 22 additions & 7 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -1840,30 +1840,45 @@ fs.FileWriteStream = fs.WriteStream; // support the legacy name


WriteStream.prototype.open = function() {
const self = this;

fs.open(this.path, this.flags, this.mode, function(er, fd) {
if (er) {
this.destroy();
this.emit('error', er);
self.destroy();
self.emit('error', er);
return;
}

this.fd = fd;
this.emit('open', fd);
}.bind(this));
self.fd = fd;
self.emit('open', fd);
});
};


function write(fd, buffer, position, callback) {
function wrapper(err, written) {
// Retain a reference to buffer so that it can't be GC'ed too soon.
callback(err, written || 0, buffer);
}

var req = new FSReqWrap();
req.oncomplete = wrapper;
binding.writeBuffer(fd, buffer, 0, buffer.length, position, req);
}


WriteStream.prototype._write = function(data, encoding, cb) {
if (!(data instanceof Buffer))
return this.emit('error', new Error('Invalid data'));
return this.emit('error', new TypeError('Invalid data'));

if (typeof this.fd !== 'number')
return this.once('open', function() {
this._write(data, encoding, cb);
});

var self = this;
fs.write(this.fd, data, 0, data.length, this.pos, function(er, bytes) {

write(this.fd, data, this.pos, function(er, bytes) {
if (er) {
self.destroy();
return cb(er);
Expand Down
14 changes: 6 additions & 8 deletions test/parallel/test-fs-write-stream-err.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
var common = require('../common');
var assert = require('assert');
var fs = require('fs');
var binding = process.binding('fs');

common.refreshTmpDir();

Expand All @@ -10,21 +11,18 @@ var stream = fs.createWriteStream(common.tmpDir + '/out', {
});
var err = new Error('BAM');

var write = fs.write;
var writeBuffer = binding.writeBuffer;
var writeCalls = 0;
fs.write = function() {
binding.writeBuffer = function() {
switch (writeCalls++) {
case 0:
console.error('first write');
// first time is ok.
return write.apply(fs, arguments);
console.error('first write');
return writeBuffer.apply(this, arguments);
case 1:
// then it breaks
console.error('second write');
var cb = arguments[arguments.length - 1];
return process.nextTick(function() {
cb(err);
});
return process.nextTick(arguments[5].oncomplete, err);
default:
// and should not be called again!
throw new Error('BOOM!');
Expand Down

0 comments on commit 65b0241

Please sign in to comment.