streams2: Allow Writables to opt out of pre-buffer-izing
authorisaacs <i@izs.me>
Tue, 9 Oct 2012 18:01:53 +0000 (11:01 -0700)
committerisaacs <i@izs.me>
Fri, 14 Dec 2012 01:00:27 +0000 (17:00 -0800)
lib/_stream_writable.js

index ce56afd..4eb2a5f 100644 (file)
@@ -27,7 +27,7 @@ module.exports = Writable
 
 var util = require('util');
 var Stream = require('stream');
-var Duplex = Stream.Duplex;
+var Duplex = require('_stream_duplex');
 
 util.inherits(Writable, Stream);
 
@@ -42,6 +42,12 @@ function WritableState(options) {
   this.ended = false;
   this.ending = false;
 
+  // should we decode strings into buffers before passing to _write?
+  // this is here so that some node-core streams can optimize string
+  // handling at a lower level.
+  this.decodeStrings = options.hasOwnProperty('decodeStrings') ?
+      options.decodeStrings : true;
+
   // not an actual buffer we keep track of, but a measurement
   // of how much we're waiting to get pushed to some underlying
   // socket or file.
@@ -74,10 +80,14 @@ Writable.prototype.write = function(chunk, encoding) {
     return;
   }
 
-  if (typeof chunk === 'string')
-    chunk = new Buffer(chunk, encoding);
-
   var l = chunk.length;
+  if (false === state.decodeStrings)
+    chunk = [chunk, encoding];
+  else if (typeof chunk === 'string' || encoding) {
+    chunk = new Buffer(chunk + '', encoding);
+    l = chunk.length;
+  }
+
   state.length += l;
 
   var ret = state.length < state.highWaterMark;
@@ -90,7 +100,11 @@ Writable.prototype.write = function(chunk, encoding) {
   }
 
   state.writing = true;
-  this._write(chunk, function writecb(er) {
+  this._write(chunk, writecb.bind(this));
+
+  return ret;
+
+  function writecb(er) {
     state.writing = false;
     if (er) {
       this.emit('error', er);
@@ -123,10 +137,8 @@ Writable.prototype.write = function(chunk, encoding) {
         this.emit('drain');
       }.bind(this));
     }
+  }
 
-  }.bind(this));
-
-  return ret;
 };
 
 Writable.prototype._write = function(chunk, cb) {