buffer: no warning when encoding isn't passed
authorTrevor Norris <trev.norris@gmail.com>
Thu, 14 Nov 2013 00:27:20 +0000 (16:27 -0800)
committerTrevor Norris <trev.norris@gmail.com>
Fri, 15 Nov 2013 19:48:03 +0000 (11:48 -0800)
Buffer#write() was showing the deprecation warning when only
buf.write('string') was passed. This is incorrect since the encoding is
always optional.

Argument order should follow:
  Buffer#write(string[, offset[, length]][, encoding])

(yeah, not confusing at all)

lib/buffer.js

index de0ab04..d5e5042 100644 (file)
@@ -75,8 +75,10 @@ function Buffer(subject, encoding) {
 
   if (!util.isNumber(subject)) {
     if (util.isString(subject)) {
-      // FIXME: the number of bytes hasn't changed, so why change the length?
-      this.length = this.write(subject, 0, encoding);
+      // In the case of base64 it's possible that the size of the buffer
+      // allocated was slightly too large. In this case we need to rewrite
+      // the length to the actual length written.
+      this.length = this.write(subject, encoding);
     } else {
       if (util.isBuffer(subject))
         subject.copy(this, 0, 0, this.length);
@@ -281,18 +283,25 @@ Buffer.prototype.set = util.deprecate(function set(offset, v) {
 // write(string, offset = 0, length = buffer.length, encoding = 'utf8')
 var writeWarned = false;
 var writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
-               ' Use write(string, offset, length, encoding) instead.';
+               ' Use write(string[, offset[, length]][, encoding]) instead.';
 Buffer.prototype.write = function(string, offset, length, encoding) {
-  // allow write(string, encoding)
-  if (util.isString(offset) && util.isUndefined(length)) {
+  // Buffer#write(string);
+  if (util.isUndefined(offset)) {
+    offset = 0;
+    encoding = 'utf8';
+
+  // Buffer#write(string, encoding)
+  } else if (util.isUndefined(length) && util.isString(offset)) {
     encoding = offset;
     offset = 0;
 
-  // allow write(string, offset[, length], encoding)
+  // Buffer#write(string, offset[, length][, encoding])
   } else if (isFinite(offset)) {
     offset = ~~offset;
     if (isFinite(length)) {
       length = ~~length;
+      if (util.isUndefined(encoding))
+        encoding = 'utf8';
     } else {
       encoding = length;
       length = undefined;