Node.js Reference · Buffers and Encoding
Node.js Buffer.byteLength() method
Reference for Buffer.byteLength() in Node.js: how many bytes a string needs in an encoding, why length is not byte count, and how it handles buffers and ArrayBuffers.
Buffer.byteLength(value, encoding) returns how many bytes a string occupies when encoded, without creating a buffer. This matters because 'héllo'.length is 5 but the text takes 6 bytes in UTF-8, and protocols such as HTTP's Content-Length header count bytes.
For a Buffer, typed array, DataView or ArrayBuffer, it returns the size of the underlying data in bytes. The default encoding for strings is 'utf8'.
Buffer.byteLength('héllo'); // 6 'héllo'.length; // 5
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
Buffer.byteLength(string[, encoding]) Buffer.byteLength(bufferLike)
| Name | Description |
|---|---|
string |
The text to measure. |
encoding |
The encoding the string would be written in. Default 'utf8'. |
bufferLike |
A Buffer, TypedArray, DataView, ArrayBuffer or SharedArrayBuffer. |
Returns: the size in bytes, as a number.
Errors: ERR_INVALID_ARG_TYPE for numbers, null and other unsupported types. An unknown encoding does not throw; the function falls back to UTF-8.
Usage notes
- UTF-8 uses 1 byte for ASCII, 2 for most Latin and Greek letters, 3 for most CJK characters and euro-like symbols, and 4 for emoji and other characters outside the BMP.
- A lone surrogate (an invalid half of an emoji) counts as 3 bytes because it is written as the replacement character.
- For
'base64'and'hex'the number is the size of the decoded bytes, estimated from the string length. For base64 it is computed from the length and the padding, so malformed input may give an estimate rather than an exact value; encode withBuffer.from()when you need the exact size. - Use it for
Content-Length, for size limits, and to allocate exactly:Buffer.allocUnsafe(Buffer.byteLength(s))thenbuf.write(s). - It is faster than
Buffer.from(string).length, because nothing is encoded or allocated. string.lengthcounts UTF-16 code units, not characters either:'😀'.lengthis 2, and[...'😀'].lengthis 1.
Related
- Buffer.from()
- buf.toString()
- Buffer encodings
- Buffer
- Tutorial: Buffers