• Node.js Video Tutorials

Node.js - Buffer.subarray() Method



The NodeJS Buffer.subarray() method returns a new buffer based on given start and end offset values on the original buffer. The new buffer has the same memory as the original buffer.

Syntax

Following is the syntax of the Node.JS Buffer.subarray() Method

buf.subarray([start[,end]])

Parameters

This method accepts two parameters but all are optional. The same is explained below.

  • start − (optional) The start index at which the new buffer will start. The default value is 0.

  • end − (optional) The end index at which the new buffer will end. The default value is buffer.length.

Return value

The method buffer.subarray() a new buffer from the original buffer.

Example

To create a buffer, we are going to make use of Buffer.from() method −

const buffer = Buffer.from('Hello');
console.log(buffer);
console.log(buffer.subarray(1,4));

Output

<Buffer 48 65 6c 6c 6f>
<Buffer 65 6c 6c>

Example

To create a buffer, we are going to make use of Buffer.alloc() method −

const buffer = Buffer.alloc(10);
console.log(buffer);
const newBuffer = buffer.subarray(1,4);
newBuffer.fill('a');
console.log(newBuffer);

Output

Using buffer.subarray() a new buffer is created from the original buffer of length 10. The new buffer is filled with the character 'a'. The output is as shown below.

<Buffer 00 00 00 00 00 00 00 00 00 00>
<Buffer 61 61 61>

Example

To create a buffer, we are going to make use of Buffer.from() method −

But will make use of negative indexes for start and end. Using a negative value for start will mean the index will take from the end of the buffer, same goes for endd.

const buffer = Buffer.from('Tutorialspoint');
console.log("The original buffer is: " + buffer);
subarray_buf = buffer.subarray(-5, -1);
console.log("The new buffer is:" + subarray_buf);
console.log(newBuffer);

Output

The original buffer is: Tutorialspoint
The new buffer is:poin
nodejs_buffer_module.htm
Advertisements