Buffer.concat
- Node.js course
- Intermediate
- Lesson 55/116
- 5 min
Learn to combine buffers with Buffer.concat.
Buffer.concat
Buffer.concat() merges an array of buffers into a single buffer. It is ideal for assembling data that arrives in pieces; for example, you can join chunks coming from a stream.
For example Buffer.concat([Buffer.from("hel"), Buffer.from("lo")]) gives a single five-byte buffer. When the result is converted with .toString() you get hello. You can pass the total length as the second argument; this prevents Node.js from computing it and speeds things up. This lets you easily join small pieces.
The totalLength parameter
You can pass a totalLength as the second argument to Buffer.concat. It is the total byte count of the resulting buffer. If you omit it, Node.js sums the lengths of all items.
For example Buffer.concat([a, b], a.length + b.length) states the total explicitly. For large arrays, computing this yourself saves time, because Node.js does not have to walk every item to sum lengths. However, if you pass a wrong totalLength, the result may be shorter or longer than expected. The safe path is to make sure your sum is correct.
Practice Concat two buffers and convert to string
Concat Buffer.from("mer") and Buffer.from("haba") with Buffer.concat. Convert to string with .toString() and print with console.log.
Starter code
// Concat two buffers with Buffer.concat
// write here
// Convert the result to string with toString
// write here
// Print with console.log
// write hereSample solution
console.log(Buffer.concat([Buffer.from("mer"), Buffer.from("haba")]).toString());Expected output
merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Buffer.concat take?
Buffer.concat([...])- A number
- A single string
- An array of buffers Correct answer
- A function
Explanation: concat takes an array of buffers and returns one buffer.
2 Complete the concat call
const result = Buffer.concat([Buffer.from("mer"), Buffer.____("haba")]);
const result = Buffer.concat([Buffer.from("mer"), Buffer.from("haba")]);
Explanation: The second piece is also made with Buffer.from.
3 Match each piece to its role
| Term | Meaning |
|---|---|
Buffer.concat |
Joins buffers |
array |
List of buffers |
toString |
Converts to string |
totalLength |
Total byte count |