What is buffer module writeInt32BE() in Node.js?

Node.js provides the buffer module to handle a fixed-length sequence of bytes. The buffer class is globally provided, so it can be used without having to use require('Buffer'). The buffer class provides many methods to allocate and manipulate buffers, including reading and writing to buffer objects.

The buffer.writeInt32BE() method writes a value to the specified offset in the buffer in the big-endian format. The value must be a 32-bit signed integer, otherwise the behavior of buffer.writeInt32Be() is undefined.

Endianness represents the order of bytes in a computer system. There are two types of endianness: little-endian and big-endian.

  • Big-endian: Big-endian stores the most significant bytes (MSB) first.

  • Little-endian: Little-endian stores the least significant bytes (LSB) first.

Prototype

buf.writeInt32BE(value[, offset])

Parameters

  • value <integer>: value is a valid 32-bit signed integer.
  • offset <integer>: offset determines the number of bytes after which the value must be written. offset must be between 0 and buffer.length - 4. The default offset is 00.

Return value

buffer.writeInt32BE() returns the offset plus the number of bytes written to the buffer.

Code

const buff = Buffer.alloc(8);
buff.writeInt32BE(0x01020304, 4);
console.log(buff)

In the code snippet above, first, we allocate a buffer of size 8 bytes using the Buffer.alloc method. This creates a buffer object of size 8-bytes and fills it with a default value of 0x00.

We then write the value 0x01020304 to the buffer object using buff.writeInt32BE(0x01020304, 4), which writes the value to the buffer at an offset of 4-bytes.

Printing the buffer object shows us that the first 4 bytes are 0x00 and our value has been successfully written to the later 4 bytes.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved