The Node.js Buffer.alloc()
method allocates a new Buffer
with a specific size.
Buffer.alloc(size, fill, encoding);
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
.TypeError
will be thrown if size
is not a number.
If size
is larger than buffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE is thrown.
If size
is 0
, a zero-length buffer will be created.
5
.0
because it is not specified.utf8
.const buf = Buffer.alloc(5); console.log(buf);
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);
We can also explicitly provide other encoding types like base64
.
const buf = Buffer.alloc(11, 'abcdefghijk', 'base64'); console.log(buf);
RELATED TAGS
CONTRIBUTOR
View all Courses