CodeBlanks Logo Icon CodeBlanks

Summary - Buffer

Combine Buffer.from, concat and toString to write a base64 converter.

Summary - Buffer

In this group you learned the core tools of buffers: creating a buffer from data with Buffer.from, joining with Buffer.concat, converting to string with toString and taking a portion with subarray.

You can combine these five tools to do a real task. For example, you can turn a string into a buffer, take a portion of it, append another buffer and print the result as text. This is a common pattern used in assembling stream data, joining file pieces or processing text. Now you will combine all pieces in one piece of code.

Practice Combine subarray and concat

Define const buf = Buffer.from("merhaba");. First print buf.subarray(0, 3).toString(). Then print Buffer.concat([buf, Buffer.from("!")]).toString() on a separate line.

Starter code

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

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

// Append "!" with Buffer.concat, print with toString
// write here

Sample solution

index.js
const buf = Buffer.from("merhaba");
console.log(buf.subarray(0, 3).toString());
console.log(Buffer.concat([buf, Buffer.from("!")]).toString());

Expected output

mer
merhaba!

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each tool to its role

Term Meaning
Buffer.from Creates a buffer from data
Buffer.concat Joins buffers
toString Converts to string
subarray Returns a view

2 Which method converts a buffer to a string?

index.js
buf.toString()
  • alloc
  • toString Correct answer
  • concat
  • from

Explanation: toString converts a buffer to a string.

3 Complete the concat call

Question
Buffer.____([buf, Buffer.from("!")])
Answer
Buffer.concat([buf, Buffer.from("!")])

Explanation: Buffer.concat joins an array of buffers.

All lessons in Intermediate