Showing with 25 additions and 8 deletions.
  1. +8 −5 doc/api/buffer.markdown
  2. +4 −1 lib/buffer.js
  3. +13 −2 test/simple/test-buffer.js
@@ -114,19 +114,22 @@ See `buffer.write()` example, above.

### buf.toJSON()

Returns a JSON-representation of the Buffer instance, which is identical to the
output for JSON Arrays. `JSON.stringify` implicitly calls this function when
stringifying a Buffer instance.
Returns a JSON-representation of the Buffer instance. `JSON.stringify`
implicitly calls this function when stringifying a Buffer instance.

Example:

var buf = new Buffer('test');
var json = JSON.stringify(buf);

console.log(json);
// '[116,101,115,116]'
// '{"type":"Buffer","data":[116,101,115,116]}'

var copy = new Buffer(JSON.parse(json));
var copy = JSON.parse(json, function(key, value) {
return value && value.type === 'Buffer'
? new Buffer(value.data)
: value;
});

console.log(copy);
// <Buffer 74 65 73 74>
@@ -379,7 +379,10 @@ Buffer.prototype.write = function(string, offset, length, encoding) {


Buffer.prototype.toJSON = function() {
return Array.prototype.slice.call(this, 0);
return {
type: 'Buffer',
data: Array.prototype.slice.call(this, 0)
};
};


@@ -833,8 +833,19 @@ Buffer(Buffer(0), 0, 0);
});


// GH-3905
assert.equal(JSON.stringify(Buffer('test')), '[116,101,115,116]');
// GH-5110
(function () {
var buffer = new Buffer('test'),
string = JSON.stringify(buffer);

assert.equal(string, '{"type":"Buffer","data":[116,101,115,116]}');

assert.deepEqual(buffer, JSON.parse(string, function(key, value) {
return value && value.type === 'Buffer'
? new Buffer(value.data)
: value;
}));
})();

// issue GH-4331
assert.throws(function() {