Skip to content
Tutorials Center
My learning

Topics

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'.

NODE
Buffer.byteLength('héllo');   // 6
'héllo'.length;               // 5

Try it

Node.js Characters versus bytes

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.

Node.js Content-Length and non-strings

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

NODE
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 with Buffer.from() when you need the exact size.
  • Use it for Content-Length, for size limits, and to allocate exactly: Buffer.allocUnsafe(Buffer.byteLength(s)) then buf.write(s).
  • It is faster than Buffer.from(string).length, because nothing is encoded or allocated.
  • string.length counts UTF-16 code units, not characters either: '😀'.length is 2, and [...'😀'].length is 1.