Writing to Buffers
You'll learn how to modify the contents of a Buffer using various write methods.
The Core Idea
While reading extracts data from a Buffer, writing lets you put new data into it. Think of a Buffer like a row of mailboxes: writing is the act of placing letters into specific boxes. Node.js provides several methods to write different types of data into Buffers, from simple strings to specific integer types.
Basic Writing with write()
The most common method is write(), which writes strings into a Buffer:
const buf = Buffer.alloc(20);
// Write a string starting at position 0
buf.write('Hello');
console.log(buf.toString()); // 'Hello'
// Write at a specific offset
buf.write(' World', 5);
console.log(buf.toString()); // 'Hello World'
// Specify encoding
buf.write('café', 0, 'utf8');
The write() method returns the number of bytes written.
Writing Integers
For binary data, use specialized methods:
const buf = Buffer.alloc(8);
// Write unsigned integers
buf.writeUInt8(255, 0); // 1 byte at position 0
buf.writeUInt16LE(1000, 1); // 2 bytes, little-endian
buf.writeUInt32BE(50000, 3);// 4 bytes, big-endian
// Write signed integers
buf.writeInt8(-42, 0);
buf.writeInt16LE(-1000, 1);
buf.writeInt32BE(-50000, 4);
The method names follow a pattern: writeInt or writeUInt (unsigned), followed by the bit size (8, 16, 32), and optionally LE (little-endian) or BE (big-endian).
Key Takeaway: Buffers are mutable—use write() for strings and writeInt/writeUInt methods for precise numerical data, always specifying the byte offset where writing should begin.