Open In App

Node.js Buffer.write() Method

Last Updated : 13 Oct, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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:

  • string: It holds the string to write into the buffer.
  • offset: It holds the number of bytes to skip before starting to write the string. Its default value is 0.
  • length: It holds the number of bytes to write into buffer. The default value is buffer.length-offset.
  • encoding: It holds the encoding of the value. The default value is ‘utf8’.

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/


Next Article

Similar Reads

three90RightbarBannerImg