From d5158574c6cb69204d155b6ea0ee4c07ab07ddd6 Mon Sep 17 00:00:00 2001 From: isaacs Date: Thu, 2 May 2013 12:25:50 -0700 Subject: [PATCH] stream: Make default encoding configurable Pretty much everything assumes strings to be utf-8, but crypto traditionally used binary strings, so we need to keep the default that way until most users get off of that pattern. --- lib/_stream_readable.js | 7 ++++++- lib/_stream_writable.js | 12 ++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index 34f714ce2c..02c41510b4 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -72,6 +72,11 @@ function ReadableState(options, stream) { // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + // when piping, we only care about 'readable' events that happen // after read()ing all the bytes and not getting any pushback. this.ranOut = false; @@ -112,7 +117,7 @@ Readable.prototype.push = function(chunk, encoding) { var state = this._readableState; if (typeof chunk === 'string' && !state.objectMode) { - encoding = encoding || 'utf8'; + encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = new Buffer(chunk, encoding); encoding = ''; diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index c060e015a0..a26f711c1d 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -68,6 +68,11 @@ function WritableState(options, stream) { var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + // 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. @@ -160,8 +165,11 @@ Writable.prototype.write = function(chunk, encoding, cb) { cb = encoding; encoding = null; } - if (!encoding) - encoding = 'utf8'; + + if (Buffer.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = function() {};