What is the Buffer.allocUnsafe function in Node.js?
The Buffer.allocUnsafe function in Node.js is used to create a buffer of any size less than the value of buffer.constants.MAX_LENGTH. Unlike the Buffer.alloc function, it does not pre-fill the buffer before allocation. These kinds of buffers are unsafe as they may contain data from previously allocated buffers.
Syntax
Buffer.allocUnsafe(length);
Parameters
The Buffer.allocUnsafe function takes in only one parameter:
- length - the size of the buffer. Determines the number of values in it.
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 example shows how to allocate an unsafe buffer of length 20:
var buf = Buffer.allocUnsafe(15);console.log(buf);
The console.log function is used to print its elements onto the console.
We can use the fill the function to remove the values already present in the buffer.
var unsafebuffer = Buffer.allocUnsafe(15);console.log("Unsafe Buffer")console.log(unsafebuffer);//Empty the unsafe buffer and fill it with 0s:unsafebuffer.fill(0);console.log("Safe Buffer")console.log(unsafebuffer);
Free Resources