• Node.js Video Tutorials

Node.js - Buffer.writeUInt16LE() Method



The NodeJS Buffer.writeUInt16LE() method helps in writing an unsigned 16-bit integer of value at a given offset to the buffer in little endian form. It returns undefined if the value is not a 16-bit unsigned integer.

Syntax

Following is the syntax of the Node.JS Buffer.writeUInt16LE() Method

buf.writeUInt16LE(value[, offset])

Parameters

This method accepts two parameters. The same is explained below.

  • value − (required)An unsigned 16-bit number to be written to the buffer.

  • offset − The offset that indicates the position to start writing. The offset is greater than or equal to 0 and also less than or equal to buffer.length-2. The default value is 0.

Return value

The method buffer.writeUInt16LE() writes the given value and returns offset plus the number of bytes written.

Example

To create a buffer, we are going to make use of NodeJS Buffer.alloc() method −

const buffer = Buffer.alloc(10);
buffer.writeUInt16LE(1000);
console.log(buffer);

Output

On execution the value starting from 0th position will be written to the buffer created. The buffer length created for the above is 10. So we can only use the offset with values from 0 to 8. If any value >8 it will give an error ERR_OUT_OF_RANGE.

<Buffer e8 03 00 00 00 00 00 00 00 00>

Example

In this example will use buffer length as 5 and offset greater than buffer.length −2 .

const buffer = Buffer.alloc(5);
buffer.writeUInt16LE(1000, 5);
console.log(buffer);

Output

internal/buffer.js:58
   throw new ERR_OUT_OF_RANGE(type || 'offset',
   ^
   
RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range. It must be >= 0 and <= 3. Received 5
PS C:\nodejsProject> node src/testbuffer.js
internal/buffer.js:58
   throw new ERR_OUT_OF_RANGE(type || 'offset',
   ^
   
RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range. It must be >= 0 and <= 3. Received 5
   at boundsError (internal/buffer.js:58:9)
   at checkBounds (internal/buffer.js:39:5)
   at checkInt (internal/buffer.js:46:3)
   at writeU_Int16LE (internal/buffer.js:556:3)
   at Buffer.writeUInt16LE (internal/buffer.js:564:10)
   at Object.<anonymous> (C:\nodejsProject\src\testbuffer.js:2:8)
   at Module._compile (internal/modules/cjs/loader.js:816:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
   at Module.load (internal/modules/cjs/loader.js:685:32)
   at Function.Module._load (internal/modules/cjs/loader.js:620:12)

Example

In this example will create a buffer and write from an offset that is within in range.

const buffer = Buffer.alloc(10);
buffer.writeUInt16LE(123, 4);
console.log(buffer);

Output

The offset has to be between 0 to 8. The output of the above code, when executed, is as shown below −

<Buffer 00 00 00 00 7b 00 00 00 00 00>
nodejs_buffer_module.htm
Advertisements