a shot of dev knowledge

RELATED TAGS

Node.js Buffer.alloc() method

The Node.js Buffer.alloc() method allocates a new Buffer with a specific size.

Syntax

Buffer.alloc(size, fill, encoding);

Parameters

  • Size: The new buffer length.
  • Fill: Pre-fill the buffer with a value. Default fill is 0.
  • Encoding: If fill is the string, then this defines the encoding type for that string. Default encoding is utf8.

Note

Example 1

  • Allocates buffer with length 5.
  • Fill is 0 because it is not specified.
  • Encoding defaults to utf8.
const buf = Buffer.alloc(5);
console.log(buf);

Example 2

  • Allocates buffer with length 8.
  • Since fill is a and default encoding is utf8, buffer fills with corresponding utf8 value character a.
const buf = Buffer.alloc(8,'a');
console.log(buf);
//buffer fills with utf8 values for the given fill-'abcde'
const buf = Buffer.alloc(5,'abcde');
console.log(buf);

Example 3

We can also explicitly provide other encoding types like base64.

const buf = Buffer.alloc(11, 'abcdefghijk', 'base64');
console.log(buf);

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring