Skip to content
Related Articles

Related Articles

Improve Article

Node.js | Buffer.allocUnsafeSlow() Method

  • Last Updated : 20 Dec, 2019

Buffer is a temporary memory storage which stores the data when it is being moved from one place to another. It’s like the array of integers. Buffer.allocUnsafeSlow() Method allocates a new buffer instance of given size but do not initialize it.

The Buffer.allocUnsafeSlow() method is used to allocate a new Buffer of given size in bytes. If the given size is greater than buffer.constants.MAX_LENGTH or less than 0, ERR_INVALID_OPT_VALUE is thrown. If the size is zero then a zero-length Buffer is created.

This method is different from Buffer.allocUnsafe() method. In allocUnsafe() method, if buffer size is less than 4KB than it automatically cut out the required buffer from a pre-allocated buffer i.e. it does not initialize a new buffer. It saves memory by not allocating many small Buffer instances. But if developer need to hold on some amount of overhead memory for intermediate amount of time, than allocUnsafeSlow() method can be used.

Syntax:

buffer.allocUnsafeSlow( size )

Parameters: This method accepts single parameter size which holds the desired size of the buffer.



Note: This method throws a TypeError if size is not a number.

Below examples illustrate the use of Buffer.allocUnsafeSlow() Method in Node.js:

Example 1:




// Node.js program to demonstrate the  
// Buffer.allocUnsafeSlow() Method
       
// Creating a buffer
const buffer = Buffer.allocUnsafe(10); 
       
// Display the buffer containing random values 
console.log("allocUnsafeSlow() Method"); 
console.log(buffer);

Output:

allocUnsafeSlow() Method
<Buffer 01 00 00 00 00 00 00 00 8b ed>

Example 2:




// Node.js program to demonstrate the  
// Buffer.allocUnsafeSlow() Method
       
// Creating a buffer
const buffer = Buffer.allocUnsafe(4); 
    
// Print: random string everytime we run the
// program as we have not added
// anything to the buffer yet
console.log(buffer.toString());
   
for (let i = 0; i < 4; i++) {
  
    //filling the values in buffer
    buffer[i] = i + 97;
}
   
// Adds and Print: 'abcd' as 97 98 99 100 101
// are their respective ASCII values
console.log(buffer.toString());

Output:

rite
abcd

Note: The above program will compile and run by using the node index.js command.

Reference: https://nodejs.org/api/buffer.html#buffer_class_method_buffer_allocunsafeslow_size




My Personal Notes arrow_drop_up
Recommended Articles
Page :