Slicing Buffers
What You'll Learn
You'll learn how to create views of a Buffer using slice() that share the same underlying memory, enabling efficient manipulation without copying data.
Understanding Buffer Slicing
When you slice a Buffer, you're not creating a completely new, independent copy of the data. Instead, you're creating a view — a window into a portion of the original Buffer's memory. Both the original Buffer and the sliced view point to the same underlying bytes in memory.
Think of it like looking at different pages of the same book through different windows. If someone edits the book, both windows show the updated content because they're viewing the same source.
The slice() Method
The slice() method takes optional start and end indices (end is exclusive, just like array slicing):
const original = Buffer.from('Hello World');
// Create a view of bytes 0-5 (indices 0,1,2,3,4)
const view = original.slice(0, 5);
console.log(view.toString()); // "Hello"
console.log(original.toString()); // "Hello World"
// Modify the view
view[0] = 74; // ASCII 'J'
// Both reflect the change!
console.log(view.toString()); // "Jello"
console.log(original.toString()); // "Jello World"
Notice how changing view also changed original — they share memory.
Why This Matters
Slicing without copying is memory-efficient. Instead of duplicating large amounts of data, you work with different views of the same memory. This is particularly useful when processing parts of large data chunks in streams.
Key Takeaway: Buffer slice() creates a view sharing the original Buffer's memory, not an independent copy — modifications to either affect both.