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
The Buffer.write() method is declared as follows:
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
startis zero.
The default value of
bytesis the difference ofand buffer.lengthreturns the number of bytes in the buffer start.
The default value of
encodingisutf-8.
The Buffer.write() method returns the number that holds the number of bytes written.
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 buffervar buf = Buffer.from ("Hello, I am good!");// Write to the bufferbuf.write("okay", 12, 4, 'utf-8');// Display resultconsole.log(buf.toString());
Free Resources