• Node.js Video Tutorials

Node.js - Buffer.includes() 方法



NodeJS 的 `buffer.includes()` 方法檢查給定值是否在緩衝區內。如果存在則返回 true,否則返回 false。

語法

以下是 NodeJS `includes()` 方法的語法:

buf.includes(value[, byteOffset][, encoding])

引數

`buffer.includes()` 方法接受三個引數。第一個引數是必需的,其餘引數都是可選的。

  • value − 此引數是必需的。這是要在緩衝區內搜尋的值。

  • byteOffset − 此引數是可選的。它指定從哪裡開始搜尋。如果給出負偏移值,則將從緩衝區的末尾開始搜尋。預設值為 0。

  • encoding − 如果要搜尋的值是字串,則可以使用此引數指定編碼。此引數是可選的。預設編碼為 utf8。

返回值

如果在緩衝區中找到該值,則 `buffer.includes()` 方法返回 true;否則返回 false。

示例

在此示例中,我們將嘗試在建立的緩衝區內搜尋一個值並測試結果。

const buffer = Buffer.from('Welcome to TutorialsPoint');

if (buffer.includes('Welcome')) {
   console.log("The string welcome is present in the buffer");
} else {
   console.log("The string welcome is not present");
}

輸出

我們正在搜尋在包含字串 "Welcome to Tutorialspoint" 的緩衝區中搜索字串 Welcome。由於給定的字串存在,因此我們得到以下輸出。

The string welcome is present in the buffer

示例

讓我們嘗試在下面的示例中使用 `byteOffset` 引數:

const buffer = Buffer.from('Welcome to TutorialsPoint');
if (buffer.includes('Point', 10)) {
   console.log("The string point is present in the buffer");
} else {
   console.log("The string point is not present");
}

輸出

我們使用了 10 作為 `byteOffset`。它將在字串 "Welcome to TutorialsPoint" 中從偏移量 10 開始搜尋。由於搜尋字串 "Point" 可用,您將得到輸出 "字串 Point 存在於緩衝區中"。

The string point is present in the buffer

示例

在此示例中,我們將使用一個緩衝區作為值來檢查它是否在給定的緩衝區內。

const buffer = Buffer.from('Welcome to TutorialsPoint');
const result  = buffer.includes(Buffer.from('TutorialsPoint'));
if (result) {
   console.log("The string TutorialsPoint is present in the buffer");
} else {
   console.log("The string TutorialsPoint is not present");
}

輸出

在 `Buffer.includes()` 方法中,我們使用了一個包含字串值 TutorialsPoint 的緩衝區。我們的主緩衝區包含字串 Welcome to TutorialsPoint。因此,由於字串存在,返回的值為 true。

The string TutorialsPoint is present in the buffer

示例

讓我們嘗試一個 false 的情況,即檢查當字串不存在時 `Buffer.includes()` 的響應。

const buffer = Buffer.from('Welcome to TutorialsPoint');

if (buffer.includes('Testing')) {
   console.log("The string Testing is present in the buffer");
} else {
   console.log("The string Testing is not present");
}

輸出

我們正在搜尋字串 Testing,它在包含字串 "Welcome to TutorialsPoint" 的緩衝區中。由於它不存在,它將返回 false。因此,您將得到輸出:字串 Testing 不存在

The string Testing is not present

示例

讓我們測試 `Buffer.includes()` 中的 `encoding` 引數。

const buffer = Buffer.from('Hello World');
if (buffer.includes('Hello','hex')) {
   console.log("The string Hello is present in the buffer");
} else {
   console.log("The string Hello is not present");
}

輸出

我們使用了 "hex" 編碼。當使用編碼檢查並且字串存在時,它返回 true。

The string Hello is present in the buffer

示例

在此示例中,我們將使用整數值,即 utf-8 編碼值,在緩衝區中進行搜尋。

const buffer = Buffer.from('Hello World');
if (buffer.includes(72)) {
   console.log("The character H is present in the buffer");
} else {
   console.log("The string H is not present");
}

輸出

這裡 72 代表根據 utf-8 編碼的字元 'H'。當在緩衝區中使用整數值進行搜尋時,它返回 true,因為字元 H 存在。

The string Hello is present in the buffer
nodejs_buffer_module.htm
廣告
© . All rights reserved.