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

The indexOf() method will return the index of the value for the search term, if the search term is present in the buffer.

  • If the search term is not found, then the method will return -1.
  • If the search term is present more than once in the buffer, then it will return only the first occurrence.

Syntax

buffer.indexOf(value, start, encoding);

Parameters

  • Value: The search term that needs to be searched in the buffer.
  • Start: Refers where to begin the search in the buffer. The default is 0.
  • Encoding: If the value is a string, then this parameter is used to specify the encoding. The default is utf8.

Example 1

In the following code snippet:

  • In line 1, we will construct the buffer object with the fill as Example buffer and store the buffer object in variable buf.
  • In line 2, we will get the index of the buffer text from buffer string buf, with the buf.indexOf('buffer') method and print it in the console.
const buf = Buffer.from('Example buffer')
console.log("Index of buffer is "+ buf.indexOf('buffer'))

Example 2

In the following code snippet:

  • In line 1, we will construct the buffer object with the fill as Example buffer and store the buffer object in variable buf.
  • In line 4, we will get the index of character e in the buffer object buf and print it in the console.

If the search term is present more than once in the buffer, then it will return only the first occurrence.

const buf = Buffer.from('Example buffer')
//here e has multiple occurrences but returns only first occurrence
console.log("Index of e is "+ buf.indexOf('e'))

Example 3

In the following code snippet:

  • In line 1, we will construct the buffer object with fill as Example buffer and store the buffer object in the variable buf.
  • In line 4, we will get the index of character z in buffer object buf, with the buf.indexOf('z') method and print it in the console.

If the search term is not found, then the method will return -1.

const buf = Buffer.from('Example buffer')
//returns -1 as z is not present in the buffer
console.log("Index of z is "+ buf.indexOf('z'))

Free Resources