CodeBlanks Logo Icon CodeBlanks

Buffer slice

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

index.js
// Define a buffer with Buffer.from
// write here

// Take first three bytes with subarray, print with toString
// write here

Sample solution

index.js
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

Question
Buffer.from("merhaba").____(0, 3)
Answer
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?

index.js
Buffer.from("merhaba").subarray(0, 3)
  • "mer" Correct answer
  • "merha"
  • "merhaba"
  • "rha"

Explanation: subarray(0, 3) gives the first three bytes: mer.

All lessons in Intermediate