Browse Source

Buffer.prototype.write: Indifferent order preference of encoding and offset

v0.7.4-release
Blake Mizerany 15 years ago
committed by Ryan Dahl
parent
commit
898afbaf34
  1. 10
      doc/api.markdown
  2. 18
      lib/buffer.js

10
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: ½ + ¼ = ¾

18
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':

Loading…
Cancel
Save