Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the use of 'Buffer.isBuffer' when you could use 'instanceof'?

Tags:

node.js

I don't understand what is the purpose of the Buffer.isBuffer function when instanceof works like a charm :

var b = new Buffer('blabla') assert.ok(b instanceof Buffer) 
like image 964
sebpiq Avatar asked Feb 18 '14 15:02

sebpiq


People also ask

What is the use of Buffer copy ()?

The Buffer. copy() method simply copies all the values from input buffer to another buffer.

What is the use of having buffers and streams when would you use it?

Buffers in Streams Streams work on a concept called buffer. A buffer is a temporary memory that a stream takes to hold some data until it is consumed. In a stream, the buffer size is decided by the highWatermark property on the stream instance which is a number denoting the size of the buffer in bytes.

Why we use buffers in Node JS?

Node provides Buffer class which provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. Buffer class is a global class that can be accessed in an application without importing the buffer module.

Is JavaScript a Buffer?

A Buffer is a temporary memory that holds data until it is consumed. A Buffer represents a fixed-size chunk of memory allocated outside of the V8 JavaScript engine. You can think of a Buffer like an array of integers that each represent a byte of data. The Buffer.


1 Answers

Well, actually these are the same (currently at least):

-- lib/buffer.js:

Buffer.isBuffer = function isBuffer(b) {   return util.isBuffer(b); }; 

-- lib/util.js:

function isBuffer(arg) {   return arg instanceof Buffer; } exports.isBuffer = isBuffer; 

... so the only possible reason is readability. Note that before this specific implementation there was a set of macros for type checks, used when building the source. But it has been changed with this commit, and that was the reasoning:

Adding macros to Node's JS layer increases the barrier to contributions, and it breaks programs that export Node's js files for userland modules. (For example, several browserify transforms, my readable-streams polyfill, the util-debuglog module, etc.) These are not small problems.

I'd suggest checking the whole discussion in the commit's pull request.

like image 52
raina77ow Avatar answered Oct 11 '22 14:10

raina77ow