Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

make JSON.stringify(buffer) not effectively blow up #3905

Closed
trentm opened this issue Aug 22, 2012 · 5 comments
Closed

make JSON.stringify(buffer) not effectively blow up #3905

trentm opened this issue Aug 22, 2012 · 5 comments
Labels

Comments

@trentm
Copy link

trentm commented Aug 22, 2012

Currently JSON.stringify on a Buffer will emit the parent "SlowBuffer", which is big. That's a pain.

> var b = new Buffer('foo');
> JSON.stringify(b)
'{"0":102,"1":111,"2":111,"length":3,"parent":{ ... lots of data

On potential solution would be to make the parent (and offset) fields of a buffer non-enumerable, then JSON.stringify (I think) wouldn't include them.

Another solution would be add a Buffer.toJSON.

In discussion with @isaacs:

isaacs: non-enumerable-ing the parent might have perf impacts, but then again, might not
that's probably ideal.
(if it's not slow)
but a toJSON would be fine, too.  maybe it could JSON like an array of ints or something?

...

Buffer.prototype.toJSON = function () { return Array.prototype.slice.call(this, 0) }
or maybe even something we could revive later:
Buffer.prototype.toJSON = function () { return {type: "buffer", data: Array.prototype.slice.call(this, 0)} }
then in your reviver, you can check if it's a {type:"buffer",data:[array]} obj, and turn those into buffers

I'd appreciate pointers on how I could try out making Buffer.{parent,offset} non-enumerable. Also, thoughts would be welcome.

@trentm
Copy link
Author

trentm commented Aug 22, 2012

FWIW, this came up in trentm/node-bunyan#35

@TooTallNate
Copy link

Buffer.prototype.toJSON = function () { return Array.prototype.slice.call(this); };

^ makes the most sense to me

@TooTallNate
Copy link

Can someone review 7cfd3951906cc6c63377c15d7a0092b57a11c180?

@TooTallNate
Copy link

@trentm Thanks, Buffer#toJSON() function added in a4ef01d.

@trentm
Copy link
Author

trentm commented Sep 10, 2012

Thanks for driving this, Nate!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

2 participants