Home > OS >  where is Buffer.forEach specified?
where is Buffer.forEach specified?

Time:10-11

I know that I can iterate over a Buffer with:

for( const b of buffer ){
  console.log(b);
}

But I noticed I can also call .forEach, .map, etc.

$ node
> const buffer = new Buffer.from([1,2,3]);
undefined
> buffer.forEach( b => console.log( b ) );
1
2
3
undefined
> buffer.map( b => 'value:'   b.toString() ).toString();
'\x00\x00\x00'

Apparently these methods are not specified on the node.js Buffer page, and also I don't understand why it behaves as it does (e.g. '\x00\x00\x00').

Where are the methods .forEach, .map, etc. on the Buffer type specified ?

CodePudding user response:

Right from the Nodejs Buffer doc.

Buffer instances are also JavaScript Uint8Array and TypedArray instances. All TypedArray methods are available on Buffers.

And, you can see all sorts of methods on a TypedArray including the ones you mention in your question.

If you go look at the implementation of the nodejs Buffer object, you will see that it is made from something they refer to as a FastBuffer. That inherits a bunch of things from Uint8Array which is likely where the methods you asked about come from:

class FastBuffer extends Uint8Array 

And, there is also a function used to populate the prototype with all sorts of additional methods here.

  • Related