What is Encoding in Buffer in Node.js Explained
encoding in a Buffer defines how text is converted to bytes or bytes back to text. It tells Node.js how to interpret the raw binary data as readable characters, such as utf8 or ascii.How It Works
Think of a Buffer as a container holding raw bytes, like a box full of puzzle pieces. Encoding is the rule that tells you how to arrange those pieces to see the full picture, which is the readable text.
When you convert a string to a buffer, encoding decides how each character turns into bytes. For example, utf8 encoding uses one to four bytes per character, while ascii uses just one byte per character but supports fewer symbols.
When reading from a buffer back to a string, encoding tells Node.js how to translate those bytes into characters correctly. Using the wrong encoding is like trying to read a book in a language you don’t understand—it looks like gibberish.
Example
This example shows how to create a buffer from a string using utf8 encoding and then convert it back to a string.
const buf = Buffer.from('Hello, world!', 'utf8'); console.log(buf); const str = buf.toString('utf8'); console.log(str);
When to Use
You use encoding in buffers whenever you need to convert between text and binary data in Node.js. This is common when reading or writing files, sending data over networks, or working with streams.
For example, if you read a text file, you specify the encoding to get the correct string. If you send text data over the internet, encoding ensures the receiver can decode it properly.
Choosing the right encoding is important for supporting different languages and symbols, especially with international text.
Key Points
- Encoding defines how text is turned into bytes and back.
utf8is the most common encoding supporting many characters.- Buffers hold raw bytes; encoding gives them meaning as text.
- Always specify encoding when converting between strings and buffers to avoid errors.