In JavaScript, a string holds text, while a Node.js Buffer holds bytes. Knowing the difference helps you read files, handle network data, encode text correctly, and avoid problems such as corrupted characters or unexpected byte counts. This guide focuses on Node.js, where Buffer is a built-in type; other programming languages may use the word “buffer” for related but different structures.
What You’ll Need
- A recent version of Node.js and a place to run JavaScript, such as a terminal or a project editor.
- Basic familiarity with variables, function calls, and strings.
- For the examples, no extra package is required:
Bufferis available globally in Node.js.
Step-by-Step
- Start by identifying whether your data is text or bytes. A string is a sequence of characters used for readable text, such as a name, a sentence, or JSON after it has been decoded. A Buffer is a sequence of byte values, usually used for data read from a file, received from a socket, or prepared for a binary format. The same information can move between these forms, but they represent it differently. For example, the word
catis text in a string and three bytes in a UTF-8 Buffer. - Check the type of a value instead of guessing. Use
typeof value === 'string'to test for a string andBuffer.isBuffer(value)to test for a Buffer. For example:const text = 'hello';
const bytes = Buffer.from(text, 'utf8');
console.log(typeof text); // string
console.log(Buffer.isBuffer(bytes)); // true
A Buffer is also a kind of typed array, so checking only whether a value is an object or array-like is not a reliable way to distinguish it. - Notice that strings are text and Buffers are measured in bytes. JavaScript strings are sequences of UTF-16 code units. That is an implementation-level detail that matters when counting: a string’s
lengthis not necessarily its number of visible characters or its number of UTF-8 bytes. A Buffer’slength, by contrast, is its number of bytes. Compare these examples:const s = 'A🙂';
console.log(s.length); // 3 UTF-16 code units
console.log(Buffer.byteLength(s, 'utf8')); // 5 bytes
console.log(Buffer.from(s, 'utf8').length); // 5 bytes
The emoji occupies two UTF-16 code units in the string and four UTF-8 bytes when encoded; the letter A adds one more byte. UseBuffer.byteLength(text, 'utf8')when you need the encoded byte count, such as for a protocol limit or a file size calculation. - Convert text to bytes with an explicit encoding. In Node.js, create a Buffer from text with
Buffer.from(text, encoding):const message = 'Hello, café';
const data = Buffer.from(message, 'utf8');
UTF-8 is a sensible default for most text formats and internet protocols, but specify the encoding when correctness depends on it. A Buffer stores the resulting bytes; it does not remember which encoding you intended. If you later decode those bytes using the wrong encoding, the output may be garbled. For binary data, do not treat arbitrary bytes as text or convert them to a string just to store them. - Convert bytes back to text only when they represent encoded text. Use the Buffer’s
toString()method and supply the matching encoding:const received = Buffer.from([72, 105]);
const decoded = received.toString('utf8');
console.log(decoded); // Hi
If the bytes contain an image, compressed file, encrypted message, or other binary format, decoding them as UTF-8 does not recover meaningful text. It can produce replacement characters or misleading output. Preserve the Buffer for binary data and use the format’s appropriate parser or decoder instead. - Choose the type that fits the task, and convert at the boundary. Use strings for editing, searching, formatting, and displaying human-readable text. Use Buffers when reading or writing raw file content, handling network chunks, processing binary formats, or passing bytes to an API that expects them. A common flow is to receive a Buffer, decode it once after confirming it contains UTF-8 text, work with a string, then encode it again when writing or sending. Keeping the conversion points clear makes it easier to spot encoding errors and avoid unnecessary work.
- Use Buffer methods for byte-level operations. A Buffer is mutable: changing a byte changes the Buffer itself. For example:
const bytes = Buffer.from('ABC', 'utf8');
bytes[0] = 97;
console.log(bytes.toString('utf8')); // aBC
Strings are immutable: an operation that appears to change a string creates a new string value instead. If you need to modify bytes, a Buffer is appropriate. If you need to preserve the original bytes, copy them first withBuffer.from(bytes); be aware that some views and slices can share underlying memory rather than making a copy.
Common Mistakes
Assuming string length equals byte length. This is false for many characters and encodings. ASCII characters often use one UTF-8 byte, but accented characters and emoji usually require more. Use Buffer.byteLength(text, 'utf8') to find the UTF-8 size, and use the Buffer’s length to count bytes already in a Buffer.
Decoding with the wrong encoding. Calling buffer.toString() defaults to UTF-8. That is convenient when the bytes are UTF-8 text, but it is not a universal way to inspect binary data. Specify the encoding when appropriate; for non-text bytes, keep them as bytes or use a format-specific tool.
Using a string for arbitrary binary content. Converting image or encrypted data to a string can lose information or make it difficult to handle safely. Keep binary content in a Buffer, or use an encoding such as Base64 only when a text-only transport requires it. Base64 is a representation of bytes, not the original binary data and not a replacement for a Buffer during byte processing.
Confusing a character, a code unit, and a byte. A visible symbol can take multiple UTF-16 code units and multiple encoded bytes. Do not use text.length as a universal measure of characters, storage, or network payload size. Decide which quantity the task requires and choose the matching operation.
Assuming a Buffer is immutable or always copied. Buffers can be modified in place. Some operations create a view over existing memory, so changing one view may affect another. If data must remain unchanged, make an explicit copy and test the behavior of the specific operation you are using.
Tips
- Write down the expected encoding at system boundaries: for example, “HTTP body is UTF-8 JSON” or “file payload is raw PNG bytes.”
- Prefer
Buffer.from(text, 'utf8')for converting known text. For a new, zero-filled buffer of a known size, useBuffer.alloc(size). - Use
Buffer.byteLength()to calculate a string’s encoded size, but do not use it to count user-perceived characters. Character counting may require Unicode-aware handling. - When joining incoming network chunks, keep them as Buffers until the complete text is available. A multibyte UTF-8 character can be split across chunks; decoding each chunk independently can introduce replacement characters. Use a streaming decoder or combine chunks before decoding.
- For debugging, inspect both representations: log the decoded text when you know it is text, and inspect byte values with methods such as
buffer.toString('hex')when investigating raw data. - Be consistent with API expectations. An API that accepts a string may encode it internally, while another API may require a Buffer. Read the documentation rather than relying on automatic conversion.
Troubleshooting
The output contains � or strange symbols. First confirm that the data is meant to be text. If it is, check how it was encoded and decode it using the same encoding. If bytes arrived in chunks, make sure you are not decoding a partial multibyte character at the end of each chunk. If the data is binary, stop converting it to a string and process it as bytes.
The payload is larger than expected. Check whether you measured characters or bytes. Log text.length, Buffer.byteLength(text, 'utf8'), and the length of the actual Buffer to compare the quantities. Also check whether your protocol adds headers, separators, or a text encoding such as Base64, which increases the transmitted size.
A function rejects the value’s type. Inspect the value immediately before the call using typeof value and Buffer.isBuffer(value). Convert only if the function’s contract calls for it. For example, use Buffer.from(text, 'utf8') when bytes are required, or buffer.toString('utf8') when the bytes are known to contain UTF-8 text.
Changing one buffer seems to change another. Look for a shared view or slice. Make a separate copy with Buffer.from(existingBuffer) before modifying it, then verify the original remains unchanged. If you are working with a typed-array view or an ArrayBuffer, check whether the constructor or method shares memory.
Data is truncated or invalid after reading. Do not assume one file or network read delivers the whole payload. Accumulate chunks until the stream ends or the required length is reached, then decode or parse the completed data. For large streams, use streaming APIs rather than collecting everything in memory.
Frequently Asked Questions
Is a Buffer just a string stored differently?
No. A string represents text as JavaScript string data, while a Buffer represents bytes. A Buffer may contain bytes that encode text, but it may also contain arbitrary binary data. Conversion between the two requires choosing or applying an encoding.
Can I use a Buffer in a browser?
Node.js provides its own global Buffer. Browsers commonly use Uint8Array and ArrayBuffer for byte data instead. Some browser projects include a Buffer-compatible library, but do not assume the Node.js global exists in every browser environment.
Does Buffer.from(text) use UTF-8?
Yes, when no encoding is supplied, Node.js uses UTF-8 for string input. Writing the encoding explicitly, as in Buffer.from(text, 'utf8'), can make the intention clearer and helps avoid confusion when handling legacy encodings.
How do I count characters rather than bytes?
There is no single count that fits every purpose. string.length counts UTF-16 code units, not necessarily visible symbols. A Unicode-aware method can count code points, while user-interface character counting may need to count grapheme clusters, which better match what people perceive as characters.
Should I convert a Buffer to a string before saving it?
Not if you are saving raw binary data. Write the Buffer directly with an appropriate file or stream API. Convert it to a string only when the data is text and you know the encoding, or when a text-based format explicitly requires a representation such as Base64.
Which should I use for JSON?
Use a string while constructing or manipulating JSON as text. When reading or writing JSON over a byte-oriented API, the content may be a Buffer; decode it using the expected text encoding, then parse the resulting string. When writing, stringify the object and encode the JSON text as required by the API.