Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

node js

What is the Buffer.allocUnsafe function in Node.js?

Rukhshan Haroon

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);

RELATED TAGS

node js

CONTRIBUTOR

Rukhshan Haroon
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring