Open In App

Node.js Buffer.writeInt16LE() Method

Last Updated : 13 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report
The Buffer.writeInt16LE() method is an inbuilt application programming interface of class Buffer within Buffer module which is used to write a valid signed 16-bit integer to buffer at the specified offset with specified little endian format. Syntax:
Buffer.writeInt16LE( value, offset )
Parameters: This method accept two parameters as mentioned above and described below:
  • value: The valid signed 16-bit integer to be written into the buffer.
  • offset: It denotes the number of bytes to be skipped before starting to write to buffer. The value of offset lies within the range 0 <= offset <= buf.length - 2. The default value of offset is 0.
Return value: It returns a buffer with the value inserted at specified offset in little endian format. Below examples illustrate the use of Buffer.writeInt16LE() Method in Node.js: Example 1: javascript
// Node.js program to demonstrate the 
// Buffer.writeInt16LE() method 
    
// Creating a buffer 
const buf = Buffer.allocUnsafe(10); 

// Using Buffer.writeInt16LE() method 
buf.writeInt16LE(0x0114, 0); 

// Display the buffer 
console.log(buf); 

// Using Buffer.writeInt16LE() method 
buf.writeInt16LE(0x1015, 2); 

// Display the buffer 
console.log(buf); 

// Using Buffer.writeInt16LE() method 
buf.writeInt16LE(0x0016, 8); 

// Display the buffer 
console.log(buf); 

// Using Buffer.writeInt16LE() method 
buf.writeInt16LE(0x0217, 6); 

// Display the buffer 
console.log(buf); 

// Using Buffer.writeInt16LE() method 
buf.writeInt16LE(0x0518, 4); 
    
// Display the result 
console.log(buf); 
Output:
<Buffer 14 01 9b 02 00 00 00 00 a8 79>
<Buffer 14 01 15 10 00 00 00 00 a8 79>
<Buffer 14 01 15 10 00 00 00 00 16 00>
<Buffer 14 01 15 10 00 00 17 02 16 00>
<Buffer 14 01 15 10 18 05 17 02 16 00>
Example 2: javascript
// Node.js program to demonstrate the 
// Buffer.writeInt16LE() method 
    
// Creating a buffer 
const buf = Buffer.allocUnsafe(6); 

// Using Buffer.writeInt16LE() method 
buf.writeInt16LE(0x2211, 0); 

// Display the buffer 
console.log(buf); 

// Using Buffer.writeInt16LE() method 
buf.writeInt16LE(0x4433, 2); 

// Display the buffer 
console.log(buf); 

// Using Buffer.writeInt16LE() method 
buf.writeInt16LE(0x6655, 4); 

// Display the buffer 
console.log(buf); 
Output:
<Buffer 11 22 00 00 00 00>
<Buffer 11 22 33 44 00 00>
<Buffer 11 22 33 44 55 66>
Note: The above program will compile and run by using the node index.js command. Reference: https://nodejs.org/dist/latest-v13.x/docs/api/buffer.html#buffer_buf_writeint16le_value_offset

Next Article

Similar Reads