Buffer slice
- Node.js course
- Intermediate
- Lesson 57/116
- 5 min
Learn to slice buffers with Buffer.slice.
Buffer slice
Sometimes you need only part of a buffer. buf.subarray(start, end) returns a view of the buffer: it does not allocate new memory, it shares the original buffer.
For example Buffer.from("hello").subarray(0, 3) gives the first three bytes (hel). start is inclusive, end is exclusive, just like string.slice. In old code you may see buf.slice(), but that method is now deprecated; use subarray instead. Because the view is shared, changes to it also affect the original buffer.
slice is deprecated
In old Node.js code you may see buf.slice(start, end). This method also returns a view like subarray, but it is deprecated. In new code you should use subarray.
Both do the same thing: they return a view that shares the original memory. However, slice may be removed in the future. That is why the official docs recommend subarray. If you see slice while reading old code, just know it means the same as subarray. This way you can understand both old and new code.
Practice Take a portion of a buffer and print it
Create a buffer with Buffer.from("merhaba"). Take the first three bytes with .subarray(0, 3), convert with .toString() and print with console.log.
Starter code
// Define a buffer with Buffer.from
// write here
// Take first three bytes with subarray, print with toString
// write hereSample solution
console.log(Buffer.from("merhaba").subarray(0, 3).toString());Expected output
mer
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the subarray call
Buffer.from("merhaba").____(0, 3)
Buffer.from("merhaba").subarray(0, 3)
Explanation: subarray returns a buffer view.
2 Match each piece to its role
| Term | Meaning |
|---|---|
subarray |
Returns a view |
start |
Start index (inclusive) |
end |
End index (exclusive) |
slice |
Deprecated |
3 What does Buffer.from("merhaba").subarray(0, 3) return?
Buffer.from("merhaba").subarray(0, 3)- "mer" Correct answer
- "merha"
- "merhaba"
- "rha"
Explanation: subarray(0, 3) gives the first three bytes: mer.