Open In App

Node.js Buffer.writeInt8() Method

Last Updated : 13 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The Buffer.writeInt8() method is an inbuilt application programming interface of class Buffer within the Buffer module which is used to writes value to an allocated buffer at the specified offset.

Syntax:

Buffer.writeInt8( value, offset )

Parameters: This method accept two parameters as mentioned above and described below:

  • value: This parameter specifies number or value to be written into the buffer. Behavior is undefined when value is anything other than integer value.
  • offset: It specifies the number of bytes to skip before starting to write or simply signify the index in the buffer. The value of offset lies 0 <= offset <= Buffer.length – 1. Its default value is 0.

Return Value: This method returns an integer value that is the sum of offset and number of bytes written.

Below examples illustrate the use of Buffer.writeInt8() method in Node.js:

Example 1:




// Node.js program to demonstrate the 
// Buffer.writeInt8() method 
       
// Allocating buffer of size 4
const buf = Buffer.allocUnsafe(4);
   
// Writing 8 bit numbers to its
// specified offset and printing
// returned value to console
console.log(buf.writeInt8(20, 0));
console.log(buf.writeInt8(-128, 1));
console.log(buf.writeInt8(-3, 2));
console.log(buf.writeInt8(127, 3));
   
// Printing buffer to console
console.log(buf);


Output:

1
2
3
4
<Buffer 14 80 fd 7f>

Example 2:




// Node.js program to demonstrate the 
// Buffer.writeInt8() method 
       
// Allocating buffer of size 2
const buf = Buffer.allocUnsafe(2);
  
// Printing the buffer before writing into it
console.log("Before writing into buffer:");
console.log(buf);
  
// Writing 8 bit signed integers
console.log(buf.writeInt8(96, 0));
console.log(buf.writeInt8(-69, 1));
  
// Printing buffer after writing
// 8 bit signed integers in it.
console.log("After writing into buffer:");
console.log(buf);


Output:

Before writing into buffer:
<Buffer 98 98gt;
1
2
After writing into buffer:
<Buffer 60 bb>

Note: The above program will compile and run by using the node index.js command.

Reference: https://nodejs.org/api/buffer.html#buffer_buf_writeint8_value_offset



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads