NodeJS Buffer.indexOf() 方法负责在缓冲区内搜索值。它返回值开始的位置,如果值不存在,则返回 -1。如果该值在缓冲区中多次出现,则将返回第一个位置。
语法
以下是NodeJS indexOf()方法的语法 -
buffer.indexOf(value, byteOffset, encoding);
参数
buffer.indexOf() 方法接受三个参数。第一个参数是必需的,其余参数是可选的。
- value − 这是一个强制性参数。它是要在缓冲区内搜索的值。该值可以是字符串、数字或缓冲区。
- byteoffset − 这是可选参数。它讲述了从哪里开始搜索的偏移量。如果给出负偏移值,它将从缓冲区的末端进行搜索。默认值为 0。
- encoding − 如果要搜索的值是字符串,则可以使用此参数给出编码。它是一个可选参数。默认情况下,使用的编码为 utf8。
返回值
Buffer.indexOf() 方法将返回它遇到的搜索值的第一个位置。如果它不存在,它将给出 -1。
例在此示例中,将尝试在创建的缓冲区内搜索值并测试结果。
const buffer = Buffer.from('Welcome to QikepuCom'); if (buffer.indexOf('Welcome') != -1) { console.log("The string welcome is present in the buffer"); } else { console.log("The string welcome is not present"); }
输出
我们正在使用字符串“Welcome to QikepuCom”创建的缓冲区中搜索字符串 Welcome。由于给定的字符串存在,我们得到下面的输出。我们检查该值是否不等于 -1。因为当我们与缓冲区中给出的值没有任何匹配时,将返回 -1。
例
让我们尝试在下面的示例中给出 byteOffset 参数 -
const buffer = Buffer.from('Welcome to QikepuComPoint'); if (buffer.indexOf('Point', 10) != -1) { console.log("The string point is present in the buffer"); } else { console.log("The string point is not present"); }
输出
我们使用 byteOffset 作为 10。它将在字符串“Welcome to QikepuComPoint”中从 10 的偏移量中搜索。由于搜索字符串:Point 可用,您将获得打印为“The string point is present in the buffer”的输出。
例
在此示例中,将使用缓冲区作为值来检查它在给定缓冲区内是否可用。
const buffer = Buffer.from('Welcome to QikepuCom'); const result = buffer.indexOf(Buffer.from('QikepuCom')); if (result != -1) { console.log("The string QikepuCom is present in the buffer"); } else { console.log("The string QikepuCom is not present"); }
输出
在 Buffer.indexOf() 方法中,我们使用了一个具有字符串值的缓冲区:QikepuCom。我们的主要缓冲区有一个字符串:Welcome to QikepuCom。因此,由于字符串存在,因此返回的值是字符串的起始位置。
例
让我们尝试一个错误的情况,即在字符串不存在时检查 Buffer.indexOf() 的响应。
const buffer = Buffer.from('Welcome to QikepuCom'); if (buffer.indexOf('Testing') != -1) { console.log("The string Testing is present in the buffer"); } else { console.log("The string Testing is not present"); }
输出
我们正在搜索字符串:使用字符串在缓冲区内进行测试:欢迎使用 QikepuCom。由于它不存在,因此它将返回值 -1。因此,您将得到以下输出: The string Testing is not present。
例
让我们测试一下 Buffer.indexOf() 内的编码参数。
const buffer = Buffer.from('Hello World'); if (buffer.indexOf('Hello','hex') != -1) { console.log("The string Hello is present in the buffer"); } else { console.log("The string Hello is not present"); }
输出
我们使用了“十六进制”编码。当检查编码并且字符串存在时,它将返回字符串的起始位置。
例
在此示例中将使用整数值,即 utf-8 编码值在缓冲区中搜索。
const buffer = Buffer.from('Hello World'); if (buffer.indexOf(72) != -1) { console.log("The character H is present in the buffer"); } else { console.log("The string H is not present"); }
输出
这里 72 代表字符“H”,按照 utf-8 编码。当在缓冲区中使用整数值进行搜索时,它将返回字符 H 的位置,因为它存在于缓冲区中。