a shot of dev knowledge

RELATED TAGS

What is the Buffer.readUInt8() method in Node.js?

The readUInt8() method reads an unsigned 8-bit integer from the buffer object at the specified offset and returns an integer.

An unsigned 8-bit integer is an unsigned whole or natural number ranging from 0 to +255.

Syntax

buffer.readUInt8( offset )

Parameters

  • offset: Number of bytes to skip before starting to read. Offset must be in the range 0 <= offset <= buf.length - 1. The default value of the offset is 0.

Code

Example 1

In the following example:

  • In line 1, we construct the buffer object from [1,255].
  • In line 4, we print an unsigned 8-bit integer of 1.
  • In line 7, we print an unsigned 8-bit integer of 255.
const buf = Buffer.from([1, 255]);

//since we passed 0 as parameter, it will first element i.e 1
console.log(buf.readUInt8(0));

//since we passed 1 as parameter, it will second element i.e 255
console.log(buf.readUInt8(1));

Example 2

In the following example:

  • In line 7, we are trying to read -2. It won’t print -2, but it prints 254, since an unsigned 8-bit integer only holds 0 to +255. So, -1 will be stored as 255, and -2 will be stored as 254.
const buf = Buffer.from([1, -2]);

//since we passed 0 as parameter, it will first element i.e 1
console.log(buf.readUInt8(0));

//since we passed 1 as parameter, it will first element i.e -2
console.log(buf.readUInt8(1));

Example 3

The method throws an error when we try to provide an offset outside of the range.

In the following code snippet, we pass offset as 3. Since it is outside of the range for the buffer object buf, it will raise the error RangeError [ERR_OUT_OF_RANGE].

const buf = Buffer.from([1, 255]);

//passing offset outside of range
console.log(buf.readUInt8(3));

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring