Usage in Deno
import { type Buffer } from "node:buffer";
Buffer.indexOf(): number
If value is:
- a string,
valueis interpreted according to the character encoding inencoding. - a
BufferorUint8Array,valuewill be used in its entirety. To compare a partialBuffer, usebuf.subarray. - a number,
valuewill be interpreted as an unsigned 8-bit integer value between0and255.
import { Buffer } from 'node:buffer'; const buf = Buffer.from('this is a buffer'); console.log(buf.indexOf('this')); // Prints: 0 console.log(buf.indexOf('is')); // Prints: 2 console.log(buf.indexOf(Buffer.from('a buffer'))); // Prints: 8 console.log(buf.indexOf(97)); // Prints: 8 (97 is the decimal ASCII value for 'a') console.log(buf.indexOf(Buffer.from('a buffer example'))); // Prints: -1 console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); // Prints: 8 const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); // Prints: 4 console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); // Prints: 6
If value is not a string, number, or Buffer, this method will throw aTypeError. If value is a number, it will be coerced to a valid byte value,
an integer between 0 and 255.
If byteOffset is not a number, it will be coerced to a number. If the result
of coercion is NaN or 0, then the entire buffer will be searched. This
behavior matches String.prototype.indexOf().
import { Buffer } from 'node:buffer'; const b = Buffer.from('abcdef'); // Passing a value that's a number, but not a valid byte. // Prints: 2, equivalent to searching for 99 or 'c'. console.log(b.indexOf(99.9)); console.log(b.indexOf(256 + 99)); // Passing a byteOffset that coerces to NaN or 0. // Prints: 1, searching the whole buffer. console.log(b.indexOf('b', undefined)); console.log(b.indexOf('b', {})); console.log(b.indexOf('b', null)); console.log(b.indexOf('b', []));
If value is an empty string or empty Buffer and byteOffset is less
than buf.length, byteOffset will be returned. If value is empty andbyteOffset is at least buf.length, buf.length will be returned.
Where to begin searching in buf. If negative, then offset is calculated from the end of buf.
encoding: BufferEncoding = 'utf8'
If value is a string, this is the encoding used to determine the binary representation of the string that will be searched for in buf.
number
The index of the first occurrence of value in buf, or -1 if buf does not contain value.