What is Buffer.alloc in Node.js?
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.
Syntax
Buffer.alloc(length, value, encoding);
Parameters
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 beutf8by default.
Only
lengthis a required parameter; the other two are optional parameters.
The Buffer.alloc function supports the following encoding types:
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.
Example
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");console.log(buf);
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');console.log(buf);
Free Resources