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

The writeInt16LE() method

The writeInt16LE() method in Node.js writes a 16-bit unsigned integer at a specified offset from a buffer in the little-endianleast significant value is stored at the lowest storage address format.

Syntax

The writeInt16LE() method can be declared as shown in the code snippet below:


Buffer.writeInt16LE(value, offset)

Parameters

  • value: This is a 16-bit signed integer to be written in the buffer.

  • offset: The offset determines the number of bytes to skip before writing to the buffer.

    In other words, it is the index of the buffer.


Note: The value of offset should be range from 0 to (bufferLength - 2). The default value of offset is 0.


Return value

The writeInt16LE() method returns an integer that has a value offset plus the number of bytes written to the buffer.

Code

The code snippet below demonstrates the use of the writeInt16LE() method:

const buff = Buffer.allocUnsafe(2);
buff.writeInt16LE(0x1234, 0);
console.log(buff);

Explanation

  • In line 1, we declare a buffer, buff.

  • In line 3, the writeInt16LE() method is used to write 16 bits from index 0 in the little-endian format.

As one index of the buffer is 8 bits, we need to write at 2 indices.

  • The writeInt16LE() method writes at 2 indices of buff, starting from index 0, that is, index = 0 - index + 2 - 1 = 1.

    Since the code is in the little-endian format, the index 1 is written before the index 0.

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