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 range0 <= offset <= buf.length - 1. The default value of the offset is0.
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 of1. - In line
7, we print an unsigned 8-bit integer of255.
const buf = Buffer.from([1, 255]);//since we passed 0 as parameter, it will first element i.e 1console.log(buf.readUInt8(0));//since we passed 1 as parameter, it will second element i.e 255console.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 prints254, since an unsigned 8-bit integer only holds0 to +255. So,-1will be stored as255, and-2will be stored as254.
const buf = Buffer.from([1, -2]);//since we passed 0 as parameter, it will first element i.e 1console.log(buf.readUInt8(0));//since we passed 1 as parameter, it will first element i.e -2console.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 rangeconsole.log(buf.readUInt8(3));