zyklus zyklus - 3 months ago 13x
Node.js Question

new node buffers already have data?

Is this a bug with node or expected behavior? Reproducible in

io 3.1.0

> new Buffer(5)
<Buffer 00 00 02 00 00>
> new Buffer(5)
<Buffer 00 00 00 00 00>
> new Buffer(5)
<Buffer 28 94 00 02 01>
> new Buffer(5)
<Buffer 00 00 00 02 00>
> new Buffer(5)
<Buffer 00 00 00 00 00>
> new Buffer(5)
<Buffer 00 98 94 00 02>


This has pretty much always been the case. Zeroing memory adds overhead, so when you create a new Buffer, you see the contents of whatever that chunk of memory contained last.

If you need/want to zero out the Buffer, just do buffer.fill(0);


With node v6.0.0 the Buffer creation API has changed. You can now directly allocate a zero-filled via Buffer.alloc(size) and get the old behavior via Buffer.allocUnsafe(size). The new Buffer()-style of Buffer creation is now considered deprecated and will be removed in a future major version (probably v8.0.0 at the earliest if I had to guess, to allow for a hard deprecation cycle).

Additionally, since node v5.10.0, you can pass the --zero-fill-buffers argument to the node binary which will silently and automatically zero-fill all Buffers upon creation.