What is includes() in Node.js Buffer Module?

The includes function in Node.js Buffer module

The includes function searches the buffer for a given value and returns whether the value was found or not. The includes function is a member of the Buffer class in the Node.js Buffer module. The syntax of the includes function is as follows:

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

Parameters

  • value is the value that is to be searched for in the buffer. It can be any of the following types:
    • string
    • Buffer
    • Uint8Array
    • integer
  • byteOffset is an integer that specifies the index of the byte in the buffer array from which searching should start. The default value is 0. If the value is a negative integer, then the index specified is calculated from the end of the buffer, where the last byte is denoted by the index -1.
  • encoding is a string that specifies the encoding type for the value parameter if it is a string. The default value is utf-8.

Return value

  • Returns a boolean value:
    • true if the value is found.
    • false if the value is not found.

Description

The includes function searches the buffer buf for the specified value.

Example usage of the includes function

The following code snippet provides various examples of how to use the includes function:

const b = Buffer.from('Hello World!');
console.log('Found "World":', b.includes('World'));
console.log('Found "World" (byteOffset = 6):', b.includes('World', 6));
console.log('Found "World" (byteOffset = 7):', b.includes('World', 7));
console.log('Found "World" (byteOffset = -6):', b.includes('World', -6));
console.log('Found "World" (byteOffset = -5):', b.includes('World', -5));
console.log('Found 72 (Ascii value for "H"):', b.includes(72)); // Ascii value for "H"

In the example above, b is a Buffer instance that contains the bytes for the string Hello World!. Several b.includes calls are made with varying parameters and the result is displayed on the standard output. The first b.includes call specifies a string World, which the buffer b contains, so the output contains true for this function call.

The second b.includes call also contains the byteOffset value, which is 6 in this case. Since the string World occurs at index 6 onwards, the result for this function call is also true.

The third b.includes call specifies 7 as the byteOffset value, so false is displayed because W, which occurs at index 6, is excluded from the searching space.

The fourth b.includes call specifies a negative byteOffset value, -6, which is the index of W, so the result is true. In the next b.includes call, the negative value for the byteOffset is -5, which represents o after the letter W, so the result is false.

In the last case, an integer (72) is specified as the value for the function call. The value 72 represents the letter H in utf-8 encoding, which is present in the buffer, so the result is true.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved