The Buffer.subarray()
method returns a subarray from the buffer. It will crop the buffer according to the given starting index
and ending index
.
Buffer.subarray( starting_index, ending_index )
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
.Cropped array points to the same memory but with cropped starting and ending indices.
In the following code snippet we will:
abcdef
to buffer object in line 1.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).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());
In the following code snippet we will:
abcdef
to buffer object in line 1.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
.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());