Buffer.byteLength()
Returns the number of bytes a string occupies in a given encoding.
Syntax
Buffer.byteLength(string[, encoding]) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
string | string | Buffer | TypedArray | Yes | The value to measure. |
encoding | string | No | Encoding for string input (default `'utf8'`). |
Returns
number — The byte length.
Examples
console.log('é'.length, Buffer.byteLength('é'));
Output
1 2
const body = JSON.stringify({ hello: 'wörld' });
res.setHeader('Content-Length', Buffer.byteLength(body));
Notes
Use this, not `String.length`, to set an accurate `Content-Length`
header: multibyte characters take more than one byte in UTF-8 so the
character count understates the size.