• Node.js Video Tutorials

Node.js - Buffer.allocUnsafeSlow() Method



The NodeJS Buffer.allocUnsafe() method helps to create a new buffer with the size given. If the size given happens to be greater than buffer.constants.MAX_LENGTH or less than 0, it will throw an error of type: ERR_INVALID_ARG_VALUE. It will throw a typeError if the size given is not a number.

The buffer created using buffer.allocUnsafeSlow() the memory allocated is not initialized and has contents which are unknown i.e it could have content of older buffers. It is also possible that it might contain sensitive data. You can make use of Buffer.fill(0) to prefill the buffer with 0.

Syntax

Following is the syntax of the NodeJS Buffer.allocUnsafeSlow() Method

Buffer.allocUnsafeSlow(size)

Parameters

This method accepts a single parameter. The same is explained below.

  • size −This is integer value and is the length for the buffer to be created.

Return value

The method Buffer.allocUnsafeSlow() will return a new buffer with the size given.

Example

In the example will create a buffer using NodeJS Buffer.allocUnsafeSlow() method −

const buf = Buffer.allocUnsafeSlow(5);
console.log(buf);

Output

The size of the buffer is 5. On executing the above program, it will generate the following output −

<Buffer 00 00 00 00 00>

Example

The example will create a buffer using Buffer.allocUnsafeSlow() method and to fill the value in the buffer will make use of Buffer.fill().

const buf = Buffer.allocUnsafeSlow(5);
buf.fill('a')
console.log(buf);

Output

The size of the buffer is 5 and we have filled the content of the buffer with value: a. On executing the above program, it will generate the following output −

<Buffer 61 61 61 61 61>

Example

In this example will see the error thrown if the size used is not a number.

const buf = Buffer.allocUnsafeSlow('5');
buf.fill('a')
console.log(buf);

Output

Since the size used is a string, it's an invalid value as size has to be an integer value. When you execute the above program, it will throw an error as shown below. On executing the above program, it will generate the following output −

TypeError [ERR_INVALID_ARG_TYPE]: The "size" argument must be of type number. Received type string
   at Function.allocUnsafeSlow (buffer.js:294:3)
   at Object.<anonymous> (C:\nodejsProject\src\testbuffer.js:1:20)
   at Module._compile (internal/modules/cjs/loader.js:816:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
   at Module.load (internal/modules/cjs/loader.js:685:32)
   at Function.Module._load (internal/modules/cjs/loader.js:620:12)
   at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)
   at internal/main/run_main_module.js:21:11
nodejs_buffer_module.htm
Advertisements