From a4ef01df07ce1d1365eec057911131c6212444f4 Mon Sep 17 00:00:00 2001 From: Nathan Rajlich Date: Sat, 8 Sep 2012 16:10:00 -0700 Subject: [PATCH] buffer: implement Buffer.prototype.toJSON() Returns an Array-representation of the Buffer. Closes #3905. --- doc/api/buffer.markdown | 19 +++++++++++++++++++ lib/buffer.js | 5 +++++ test/simple/test-buffer.js | 4 ++++ 3 files changed, 28 insertions(+) diff --git a/doc/api/buffer.markdown b/doc/api/buffer.markdown index 3be63e79123..d96f4acf6cd 100644 --- a/doc/api/buffer.markdown +++ b/doc/api/buffer.markdown @@ -108,6 +108,25 @@ Decodes and returns a string from buffer data encoded with `encoding` 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` implictly 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]' + + var copy = new Buffer(JSON.parse(json)); + + console.log(copy); + // + ### buf[index] diff --git a/lib/buffer.js b/lib/buffer.js index 3001945620e..cdc0f4b0a53 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -411,6 +411,11 @@ Buffer.prototype.write = function(string, offset, length, encoding) { }; +Buffer.prototype.toJSON = function() { + return Array.prototype.slice.call(this, 0); +}; + + // toString(encoding, start=0, end=buffer.length) Buffer.prototype.toString = function(encoding, start, end) { encoding = String(encoding || 'utf8').toLowerCase(); diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js index 8ab8568c27d..c6d2a9ff2df 100644 --- a/test/simple/test-buffer.js +++ b/test/simple/test-buffer.js @@ -748,3 +748,7 @@ Buffer(Buffer(0), 0, 0); 'new gnu gun' ].forEach(function(enc) { assert.equal(Buffer.isEncoding(enc), false); }); + + +// GH-3905 +assert.equal(JSON.stringify(Buffer('test')), '[116,101,115,116]');