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:

  • 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:



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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());

chevron_right


Output:

GEEksforGeeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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());

chevron_right


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/

My Personal Notes arrow_drop_up

innovative programmer

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.