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
buffer class provides many methods to allocate and manipulate
buffers, including reading and writing to
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.
valueis a valid 32-bit signed integer.
offsetdetermines the number of bytes after which the
valuemust be written.
offsetmust be between 0 and
buffer.length - 4. The default
buffer.writeInt32BE() returns the
offset plus the number of bytes written to the buffer.
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
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.
buffer object shows us that the first 4 bytes are
0x00 and our value has been successfully written to the later 4 bytes.
View all Courses