What is the Node.js Buffer.subarray() method?

The Buffer.subarray() method returns a subarray from the buffer. It will crop the buffer according to the given starting index and ending index.

Syntax

Buffer.subarray( starting_index, ending_index )

Parameters

  • starting index: An integer value that denotes the starting address of the buffer. The default is 0.
  • ending index: An integer value that denotes the ending address of the buffer. The default is Buffer length.

Return value

Cropped array points to the same memory but with cropped starting and ending indices.

Example 1

In the following code snippet we will:

  • Convert the fill abcdef to buffer object in line 1.
  • Print out the original buffer object in line 2.
  • Line 4 crops the buffer with buf.subarray(1,3) and stores the cropped buffer object in cropped_buf variable. Here the starting index is 1 and the ending index is 3(not inclusive).
  • Line 5 prints the cropped array as string for readability purpose.

The toString() method will convert objects to the string format on which it is called.

const buf = Buffer.from('abcdef', 'ascii');
console.log("Original Buffer: "+ buf);
cropped_buf = buf.subarray(1,3);
console.log("Cropped Buffer: "+ cropped_buf.toString());

Example 2

In the following code snippet we will:

  • Convert the fill abcdef to buffer object in line 1.
  • Print out the original buffer object in line 2.
  • In line 4, buf.subarray(-3,-1) will crop the buffer and store the cropped buffer object in cropped_buf variable. Here -3 is the starting index and -1 is the ending index. Since the ending index is not inclusive, it crops until -2.
  • Line 5 prints the cropped array as string for readability purpose.

Indices can be negative too. We assign negative indices from right to left ( -1 as last element in the buffer, -2 as last but one element in the buffer, etc.).

const buf = Buffer.from('abcdef', 'ascii');
console.log("Original Buffer: "+ buf);
cropped_buf = buf.subarray(-3,-1);
console.log("Cropped Buffer: "+cropped_buf.toString());