What is the Node.js Buffer.isBuffer() method?
A Buffer is a temporary memory that holds data until it is consumed. A Buffer represents a
You can think of a Buffer like an array of integers that each represent a byte of data.
The Buffer.isBuffer() method of the Buffer object is used to check if an object is a Buffer or not.
isBufferis implemented by the Node.jsBufferclass.
Bufferand its methods do not need to be imported, asBufferis a global class.
Syntax
Buffer.isBuffer([object])
Parameters
[object]: A required parameter that is the object to check if it is aBufferor not.
Return value
isBuffer() returns a Boolean value that can be true or false. The method returns true if [object] is a Buffer; otherwise, it returns false.
Example
In the example below, we test different objects to see if they are Buffers.
// create a real Buffer objectconst buf = Buffer.from("A buffer")// creating other objctsconst name = "Theodore"const ourObj = {}const ourArr = []// Checking to see if they are buffersconsole.log(Buffer.isBuffer(name)) // falseconsole.log(Buffer.isBuffer(ourObj)) // falseconsole.log(Buffer.isBuffer(ourArr)) // falseconsole.log(Buffer.isBuffer(buf)) // true
In the code above, ourObj is not a Buffer because it is just a plain Javascript object. The array ourArr is also just a Javascript array object. Likewise, the string name is just a string and not a Buffer instance.
As we have seen, the isBuffer() method is used to check if an object is actually a Buffer.