buffer: implement Buffer.prototype.toJSON()
Returns an Array-representation of the Buffer. Closes #3905.
This commit is contained in:
parent
8e0c830cd0
commit
a4ef01df07
@ -108,6 +108,25 @@ Decodes and returns a string from buffer data encoded with `encoding`
|
|||||||
See `buffer.write()` example, above.
|
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);
|
||||||
|
// <Buffer 74 65 73 74>
|
||||||
|
|
||||||
### buf[index]
|
### buf[index]
|
||||||
|
|
||||||
<!--type=property-->
|
<!--type=property-->
|
||||||
|
@ -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)
|
// toString(encoding, start=0, end=buffer.length)
|
||||||
Buffer.prototype.toString = function(encoding, start, end) {
|
Buffer.prototype.toString = function(encoding, start, end) {
|
||||||
encoding = String(encoding || 'utf8').toLowerCase();
|
encoding = String(encoding || 'utf8').toLowerCase();
|
||||||
|
@ -748,3 +748,7 @@ Buffer(Buffer(0), 0, 0);
|
|||||||
'new gnu gun' ].forEach(function(enc) {
|
'new gnu gun' ].forEach(function(enc) {
|
||||||
assert.equal(Buffer.isEncoding(enc), false);
|
assert.equal(Buffer.isEncoding(enc), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
// GH-3905
|
||||||
|
assert.equal(JSON.stringify(Buffer('test')), '[116,101,115,116]');
|
||||||
|
Loading…
x
Reference in New Issue
Block a user