Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What is Buffer.alloc in Node.js?

Rukhshan Haroon

The Buffer.alloc function is part of the Buffer module in Node.js and is used to allocate a buffer of any size less than the constant value of buffer.constants.MAX_LENGTH.


Buffer.alloc(length, value, encoding);


The Buffer.alloc function takes up to three arguments:

  • length: the length of the buffer.

  • value: the value to be stored in the buffer. The value is replicated to fill the buffer.

  • encoding: the encoding of the value. If the value is a string, the encoding is assumed to be utf8 by default.

Only length is a required parameter; the other two are optional parameters.

The Buffer.alloc function supports the following encoding types:

%0 node_1625557829893 binary node_1625557822712 ascii node_1625557827696 latin1 node_1 ucs2 node_1625557815600 utf-16le node_1625557854896 utf-8 node_1625557816142 base64 node_1625557867680 hex

Return value

If the size of length is greater than buffer.constants.MAX_LENGTH or smaller than 0, the error ERR_INVALID_ARG_VALUE is raised. The function does not return anything otherwise.


The following code snippet below shows how to allocate a buffer of size 15 and in hex encoding. The value is in base 10. In hex, 88 converts to 58. The buffer is shown as output in the console, using the console.log function.

var buf = Buffer.alloc(15, 88, "hex");

Here, the prescribed value is of type string. Hence, the encoding has been selected as utf-8 by default. Since the value of the character e is 65 in hex, the buffer is filled with 20 values of 65. Note that 20 is the prescribed length of the buffer.

var buf = Buffer.alloc(20, 'e');




Rukhshan Haroon
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring