toString and encoding
- Node.js course
- Intermediate
- Lesson 56/116
- 5 min
Learn Buffer.toString and encoding.
toString and encoding
To turn a buffer into a string you use toString(). The default encoding is utf8, so buf.toString() gives back the text. You can also choose other encodings.
Three common encodings: utf8 (text), hex (hexadecimal) and base64. For example Buffer.from("book").toString("base64") gives Ym9vaw==. toString("hex") writes each byte as two hex digits. This lets you safely carry binary data over a text channel.
Encoding types
Each encoding has a different use case. utf8 is the standard for text data and shows special characters correctly. hex writes each byte as two characters, useful for carrying small binary data.
base64 packs binary data into ASCII text, common for email attachments and data URIs. For example Buffer.from("Node").toString("hex") gives 4e6f6465. Which encoding you choose depends on where the data goes: utf8 for text, hex for digests, base64 for transport.
Practice Print a buffer as both text and hex
Create a buffer with Buffer.from("Node"). Print the plain text with .toString() and the hex form with .toString("hex") on separate lines using console.log.
Starter code
// Define a buffer with Buffer.from
// write here
// Print plain text with toString
// write here
// Also print in hex form
// write hereSample solution
const buf = Buffer.from("Node");
console.log(buf.toString());
console.log(buf.toString("hex"));Expected output
Node 4e6f6465
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which encoding gives base64 output?
buf.toString("base64")- utf8
- hex
- ascii
- base64 Correct answer
Explanation: toString("base64") gives base64 output.
2 hex encoding
const buf = Buffer.from("Node"); console.log(buf.toString("____"));
const buf = Buffer.from("Node"); console.log(buf.toString("hex"));
Explanation: toString("hex") gives hexadecimal output.
3 Match each encoding to its role
| Term | Meaning |
|---|---|
utf8 |
Standard for text |
hex |
Hexadecimal output |
base64 |
ASCII compression |
ascii |
7-bit English |