Skip to content

Buffer

Buffer objects are used to represent a fixed-length sequence of bytes. They extends Uint8Array and you can often use them interchangeably with some APIs.

Allocate n bytes

Snippet below allocates 1024 bytes:

const buf = new Buffer(1024);

Create buffer from string

const buf = Buffer.from("Hello World");

Generate random n bytes

const buf = Buffer.random(16);

Create string from buffer

const buf = Buffer.from("Hello");
console.log(buf.toString('utf8')); // Hello
console.log(buf.toString('hex')); // 48656c6c6f
console.log(buf.toString('base64')); // SGVsbG8=
console.log(buf.toString('base64url')); // SGVsbG8