Open In App

Node.js Buffer.write() Method

The Buffer.write() method writes the specified string into a buffer, at the specified position. If buffer did not contain enough space to fit the entire string, only part of string will be written. However, partially encoded characters will not be written.

Syntax:



buffer.write( string, offset, length, encoding )

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

Return Value: This method returns a number that represents the number of bytes written.



Example 1:




// Node.js program to demonstrate the  
// Buffer.write() method 
  
// Create a buffer
var buf = Buffer.from('GeeksforGeeks');
  
buf.write('EE', 1);
   
console.log(buf.toString());

Output:

GEEksforGeeks

Example 2:




// Node.js program to demonstrate the  
// Buffer.write() method 
  
// Create a buffer
const buf = Buffer.allocUnsafe(100);
   
const len = buf.write('GeeksforGeeks', 2, 5, 'utf8');
   
console.log(len.toString());

Output:

5

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

Reference: https://www.geeksforgeeks.org/node-js-buffer-allocunsafe-method/amp/

Article Tags :