Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

node.js

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

Umme Ammara

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

RELATED TAGS

node.js

CONTRIBUTOR

Umme Ammara
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring