Buffer.isBuffer()
Tests whether a value is a Buffer instance.
Syntax
Buffer.isBuffer(obj) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
obj | any | Yes | The value to test. |
Returns
boolean — true if obj is a Buffer.
Examples
console.log(Buffer.isBuffer(Buffer.from('x')));
console.log(Buffer.isBuffer('x'));
Output
true
false
function toText(data) {
return Buffer.isBuffer(data) ? data.toString('utf8') : String(data);
}
console.log(toText(Buffer.from('hi')));
Output
hi
Notes
Useful when an API may hand back either a string or a Buffer (e.g.
`fs.readFile` with or without an encoding). Note a Buffer is also a
`Uint8Array`, so `instanceof Uint8Array` is true too.