Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

How to use the buf.lastIndexOf() function in Node.js

Ayesha Naeem

A buffer buf calls the buf.lastIndexof() function on a value and returns the index of where that value last occurred in the buffer.


Parameters and return value

The buf.lastIndexOf() function accepts three parameters:

  • value: The buf.lastIndexOf() function returns the last occurrence of the value in the buffer buf. It can be of type string, buffer,integer, or Uint8Array.
  • byteoffset: This indicates where to begin the search in the buffer buf, and it is set to buf.length -1 by default. If the byteoffset is negative, it is set to the end of the buffer buf. The byteoffset is of type integer.
  • encoding: This determines the binary representation of the value if it is of type string. It is set to utf-8 by default.

The buf.lastIndexOf() function returns an integer indicating the index where the value lies in the buffer buf and returns -1 if the value does not exist in buf.

Note: The program will throw a TypeError if the value is not a string, buffer, or integer.


The following code demonstrates how to use the Buffer.lastIndexOf() function in Node.js.

// create a buffer
var buf = Buffer.from("")
//call the lastIndexOf() function
// set the offset to the 7th byte
//input the value as the value of c
//input an out of range number. 97 is the ascii of a.
//input the value as a buffer

The above program applies the buf.lastIndexOf() function on values of type string, buffer, and integer.

  • The program calls the lastIndexOf() function on a buffer created with a string, and then it holds the indexes of that string’s characters in the buffer.
  • The program then inputs an integer, which is treated as an ASCII value, and the index of the corresponding character is returned.
  • When an out-of-range ASCII value is input to the function, the program truncates the value and returns the character corresponding to the truncated value.
  • The program also uses another buffer to test the lastIndexOf() function and returns the index from where the other buffer starts.

Note: If the value is a number outside of the range 0-255, the number is converted into a valid byte integer. If the byteoffset is not a valid byte, it is converted into a valid byte. The entire buffer is searched if the byteoffset is converted to 0 or NaN.



Ayesha Naeem
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring