Node.js Buffer.indexOf() Method
Last Updated :
13 Oct, 2021
Improve
Buffer is a temporary memory storage which stores the data when it is being moved from one place to another. It is like the array of integers.
The Buffer.indexOf() method firstly checks for the input value, if it present in the buffer then it returns the first position (index) from where the value is starting.
Syntax:
javascript
Output:
javascript
Output:
buffer.indexOf( value, start, encoding )Parameters: This method accept three parameters as mentioned above and described below:
- value: This parameter holds the value that you want to find in the buffer.
- start: It is an optional parameter. It refers to the starting index from which the elements of input buffer will be searched. The default value is 0.
- encoding: It is an optional parameter. If the needed value is string, then you can add the encoding type. The default value is utf-8.
// Node.js program to demonstrate the
// Buffer.indexOf() method
// Creating a buffer
const buffer = Buffer.from(
'GeeksforGeeks: A computer science portal');
const output = buffer.indexOf('computer');
console.log(output);
17Example 2:
// Node.js program to demonstrate the
// Buffer.indexOf() method
const buffer = Buffer.from('geeks community');
const output = buffer.indexOf(101);
// Print: 1 as 101 is the ASCII value of 'e'
// and 'e' occurs first at index 1
const output1 = buffer.indexOf('geeks community');
// Print: 0 as the whole value starts from 0 index only
const output2 = buffer.indexOf('geeks', 6);
// Print: -1 as we are starting the search from
// 6 index but 'geek' is not present before it
console.log(output);
console.log(output1);
console.log(output2);
1 0 -1Note: The above program will compile and run by using the
node index.js
command.
Reference: https://nodejs.org/api/buffer.html#buffer_buf_indexof_value_byteoffset_encoding