Buffer.from
- Node.js course
- Intermediate
- Lesson 54/116
- 5 min
Learn to create buffers with Buffer.from.
Buffer.from
Buffer.from() creates a buffer from existing data. You can pass a string, an array or another buffer. The most common use is making a buffer from a string.
For example Buffer.from("hello") returns a five-byte buffer; each byte corresponds to a letter. The buf.length property returns 5. You can also pass an encoding as the second argument: Buffer.from("QXs=", "base64") decodes the base64 string into bytes. This lets you create buffers from both plain text and encoded data.
Buffer with encoding
You can pass an encoding as the second argument to Buffer.from. It tells how the string should be interpreted. The default is utf8.
For example Buffer.from("4e6f64", "hex") makes a three-byte buffer, because every two hex digits form one byte. Buffer.from("QXs=", "base64") decodes a base64 string. Calling Buffer.from(123) without a string throws an error; numeric values must be converted to a string first. This lets you safely create buffers from different sources.
Practice Create a buffer with Buffer.from and print its length
Create a buffer with Buffer.from("merhaba"). Print its length using .length with console.log.
Starter code
// Define a buffer with Buffer.from
// write here
// Get its length property
// write here
// Print with console.log
// write hereSample solution
const buf = Buffer.from("merhaba");
console.log(buf.length);Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Create a buffer from a string
const buf = Buffer.____("merhaba");
const buf = Buffer.from("merhaba");
Explanation: Buffer.from creates a buffer from data.
2 What does Buffer.from("merhaba").length return?
Buffer.from("merhaba").length- 5
- 7 Correct answer
- 6
- 8
Explanation: 'merhaba' has seven letters; each letter is one byte.
3 Match each piece to its role
| Term | Meaning |
|---|---|
Buffer.from |
Creates a buffer from data |
"merhaba" |
Source string |
buf.length |
Gives byte count |
encoding |
Coding format |