What is Buffer Module write() in Node.js?

The Buffer.write() method writes a specified string into the buffer at a specified position. To use the buffer module directly, you can install it using npm, as shown below:

npm install buffer

Syntax

The Buffer.write() method is declared as follows:

Parameters

The method takes four parameters:

  • value: This is the string that we wish to write into the buffer.

  • start: This holds the number of bytes to skip before writing into the buffer.

  • bytes: This is the number of bytes to write into the buffer.

  • encoding: This holds the value of the encoding.

The default value of start is zero.

The default value of bytes is the difference of buffer.lengthreturns the number of bytes in the buffer and start.

The default value of encoding is utf-8.

Return value

The Buffer.write() method returns the number that holds the number of bytes written.

Example

The following code shows the use of the Buffer.write() method.

First, a buffer is created with a string as the parameter. We then call the buf.write method by providing the parameters. Finally, the result is displayed by converting the buffer to the string format.

// Create a buffer
var buf = Buffer.from ("Hello, I am good!");
// Write to the buffer
buf.write("okay", 12, 4, 'utf-8');
// Display result
console.log(buf.toString());

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved