Node.js Reference ยท Buffers and Encoding
Node.js Buffer.isBuffer() method
Reference for Buffer.isBuffer() and Buffer.isEncoding() in Node.js: test whether a value is a Buffer or a known encoding name, and how it differs from Uint8Array checks.
Buffer.isBuffer(value) returns true if the value is a Buffer instance and false for everything else, including plain Uint8Arrays, strings and null. Because Buffer extends Uint8Array, every buffer is also a Uint8Array, but not the other way around.
Its companion Buffer.isEncoding(name) tells you whether a string is an encoding name that Node.js understands, which is useful before passing user-supplied names to toString() or Buffer.from().
Buffer.isBuffer(Buffer.alloc(1)); // true Buffer.isBuffer(new Uint8Array(1)); // false Buffer.isEncoding('utf-8'); // true
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
Buffer.isBuffer(obj) Buffer.isEncoding(encoding)
| Name | Description |
|---|---|
obj |
Any value. |
encoding |
A string to test as an encoding name. |
Returns: a boolean. isEncoding() is case-insensitive and also accepts aliases such as 'UTF-8', 'binary' (for latin1) and 'ucs-2'. Non-strings and empty strings give false.
Errors: none; both functions accept any value.
Usage notes
Buffer.isBuffer()is aninstanceof Bufferstyle check. A plainUint8Arrayreturnsfalseeven though it holds bytes; testvalue instanceof Uint8Arrayto accept both.- Only real instances count: an object with a
Buffer-like shape does not, and neither doesBuffer.prototypeitself. ArrayBuffer.isView(value)is true for buffers, typed arrays andDataViews. It is the right check for "some binary view".- Buffers sent through
postMessage()or structured clone arrive as plainUint8Arrays; convert withBuffer.from(u8.buffer, u8.byteOffset, u8.byteLength), which does not copy. isEncoding()helps reject badencodingarguments early, instead of gettingERR_UNKNOWN_ENCODINGfrom a deeper call.
Related
- Buffer
- Buffer.from()
- Buffer encodings
- Tutorial: Buffers