diff --git a/doc/api.markdown b/doc/api.markdown index e77756f429..e1c405d0f1 100644 --- a/doc/api.markdown +++ b/doc/api.markdown @@ -76,7 +76,7 @@ Allocates a new buffer using an `array` of octets. Allocates a new buffer containing the given `str`. -### buffer.write(string, encoding, offset) +### buffer.write(string, offset=0, encoding='utf8') Writes `string` to the buffer at `offset` using the given encoding. Returns number of octets written. If `buffer` did not contain enough space to fit @@ -85,11 +85,9 @@ of `'utf8'` encoding, the method will not write partial characters. Example: write a utf8 string into a buffer, then print it - var Buffer = require('buffer').Buffer, - buf = new Buffer(256), - len; - - len = buf.write('\u00bd + \u00bc = \u00be', 'utf8', 0); + Buffer = require('buffer').Buffer; + buf = new Buffer(256); + len = buf.write('\u00bd + \u00bc = \u00be', 0); console.log(len + " bytes: " + buf.toString('utf8', 0, len)); // 12 bytes: ½ + ¼ = ¾ diff --git a/lib/buffer.js b/lib/buffer.js index 66401b4460..797d4d67e6 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -38,8 +38,22 @@ Buffer.prototype.toString = function (encoding, start, stop) { } }; -Buffer.prototype.write = function (string, encoding, offset) { - encoding = (encoding || 'utf8').toLowerCase(); +Buffer.prototype.write = function (string) { + // Support both (string, offset, encoding) + // and the legacy (string, encoding, offset) + var offset, encoding; + + if (typeof arguments[1] == 'string') { + encoding = arguments[1]; + offset = arguments[2]; + } else { + offset = arguments[1]; + encoding = arguments[2]; + } + + offset = offset || 0; + encoding = encoding || 'utf8'; + switch (encoding) { case 'utf8': case 'utf-8':