What is the writeUInt8 function in Node.js?

The writeUInt8 function in Node.js comes with the Buffer module and is used to write an 8-bit unsigned integer to a buffer at a specified offset.

Syntax

To use the writeUInt8 function, we would need a pre-allocated buffer. For this tutorial, we have named it mybuffer. The following syntax is used to use the writeUInt8 function:

mybuffer.writeUInt8(value, offset);

Parameters

The writeUInt8 function takes in up to two parameters:

  • value: the unsigned 8-bit integer that needs to be written to a pre-allocated buffer.
  • offset (optional): the offset at or the number of bytes after which value will be written to in the buffer. The minimum value of offset is 0, and its maximum value is one less than the value of mybuffer.lenwhich is the number of bytes in the buffer.

If offset is not specified, it is assumed to be 0 by default. If the value of offset is out of the prescribed range, the ERR_OUT_OF_RANGE error is thrown. If value is greater than 8 bits, the function exhibits undefined behavior.

Return value

The writeUInt8 returns the sum of the offset and the number of bytes written to the buffer upon successful execution.

Example

The program below allocates a buffer of length 5. Subsequently, it uses the writeUInt8 function to write an 8-bit unsigned integer to mybuffer at a specified offset and prints the current state of mybuffer using the console.log function.

The program fills mybuffer from 0 to 4 in reverse order and prints its final state before terminating.

mybuffer = Buffer.alloc(5);
console.log(mybuffer);
mybuffer.writeUInt8(0x01, 4);
console.log(mybuffer);
mybuffer.writeUInt8(0x02, 3);
console.log(mybuffer);
mybuffer.writeUInt8(0x03, 2);
console.log(mybuffer);
mybuffer.writeUInt8(0x04, 1);
console.log(mybuffer);
mybuffer.writeUInt8(0x05, 0);
console.log(mybuffer);
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved