How to use the buf.indexOf() function in Node.js
The buf.indexof() function takes a value and returns the index of where that value first occured in the buffer.
Prototype
Parameters and return value
The buf.indexOf() function accepts three parameters:
value: Thebuf.indexOf()function returns the first occurrence ofvaluein the buffer (buf).valuecan be of typestring,buffer,integer, andUint8Array.byteoffset: Indicates where to begin the search in the buffer (buf), and is set to 0 by default. Ifbyteoffsetis negative, it is set to the end of the buffer (buf).byteoffsetis of typeinteger.encoding: Determines the binary representation of thevalueif it is of typestring.encodingis set toutf-8by default.
The buf.indexOf() function returns an integer indicating the index at which the value lies in the buffer (buf), and returns -1 if the value does not exist in buf.
Note: The program will throw a
TypeErrorifvalueis not a string, buffer, or integer.
Examples
The following code demonstrates how to use the Buffer.indexOf() function in Node.js.
// create a buffervar buf = Buffer.from("Educative.io")//call the indexOf() functionconsole.log(buf.indexOf('e'))// set the offset to the 4th byteconsole.log(buf.indexOf('i',4))//input the ascii value of cconsole.log(buf.indexOf(99))//input an out of range number. 97 is the ascii of a.console.log(buf.indexOf(97+256))//input the value as a bufferconsole.log(buf.indexOf(Buffer.from('tive.io')))
The above program applies the buf.indexOf() function on values of type string, buffer, and integer.
- The program calls the
indexOf()function on a buffer created with a string and obtains the indexes of the string’s characters in the buffer. - The program then inputs an
, and the index of the corresponding character is returned.integer is treated as an ASCII value - 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 uses another buffer to test the
indexOf()function and returns the index from where the other buffer starts.
Note: If
valueis a number outside of the range 0-255, the number is converted into a valid byte integer. Ifbyteoffsetis not a valid byte, it is converted into a valid byte. The entire buffer is searched ifbyteoffsetis converted to 0 or NaN.
Free Resources