Buffer vs array
1. How to create a new Buffer
Node.js offers several ways to create a buffer:
Buffer.from()
Creates a buffer from existing data (a string, an array of bytes, another buffer):
const buf1 = Buffer.from('Hello', 'utf8'); // from a string
const buf2 = Buffer.from([72, 101, 108, 108, 111]); // from an array of numbersBuffer.alloc(size)
Creates a new buffer of a given size, filled with zeros:
const buf3 = Buffer.alloc(10); // 10 bytes, all 0The safe option, it clears the memory before use.
Buffer.allocUnsafe(size)
Creates a buffer of the given size, but without zeroing the memory (it may contain "garbage" left over from previous data):
const buf4 = Buffer.allocUnsafe(10);Used when maximum speed matters, and you're certain you'll write every byte manually.
Buffer.concat(list)
Joins several buffers into one:
const part1 = Buffer.from('Hello ');
const part2 = Buffer.from('World');
const buf = Buffer.concat([part1, part2]);
console.log(buf.toString()); // "Hello World"2. How Buffer differs from a regular array
| Criterion | Buffer | Array |
|---|---|---|
| Data type | Stores bytes (numbers 0-255) | Can store any value (numbers, strings, objects, etc.) |
| Size | Fixed, its length can't change after creation | Dynamic, elements can be added and removed |
| Performance | Runs at the C++ level, very fast for binary operations | Slower, since it's implemented at the JS level |
| Purpose | For binary data (files, network, streams) | For logical data and structures in JS |
| Memory | Lives in unmanaged memory (outside the V8 heap) | Lives in V8's managed memory |
| Encoding | Supports reading/writing strings in different encodings (utf8, hex, base64) | Has no direct encoding support |
| Methods | Has low-level methods (readUInt8, writeUInt16LE, slice, toString) | Regular array methods (map, forEach, push) |
An example of the differences:
const arr = [72, 101, 108, 108, 111];
const buf = Buffer.from(arr);
console.log(arr); // [72, 101, 108, 108, 111]
console.log(buf); // <Buffer 48 65 6c 6c 6f>
console.log(arr.map(x => String.fromCharCode(x)).join('')); // "Hello"
console.log(buf.toString('utf8')); // "Hello"Both hold the same numbers,
but Buffer is optimized for working with bytes, while Array is for logic at the JS level.
Summary
Bufferis a special type for storing and processing binary data, created viaBuffer.from(),Buffer.alloc(),Buffer.allocUnsafe(), orBuffer.concat().It differs from a regular array in that it:
- stores only bytes (0-255),
- has a fixed size,
- runs faster and closer to the hardware,
- is used in every I/O operation in Node.js.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.