The indexOf()
method will return the index of the value for the search term, if the search term is present in the buffer.
-1
.buffer.indexOf(value, start, encoding);
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
.In the following code snippet:
Example buffer
and store the buffer object in variable buf
.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'))
In the following code snippet:
Example buffer
and store the buffer object in variable buf
.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 occurrenceconsole.log("Index of e is "+ buf.indexOf('e'))
In the following code snippet:
Example buffer
and store the buffer object in the variable buf
.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 bufferconsole.log("Index of z is "+ buf.indexOf('z'))