How can I know that how much data is transferred over wire in terms of size in kilobytes, megabytes?
Take for example
{ 'a': 1, 'b': 2 }
How do I know what is the size of this payload is and not the length or items in the object
UPDATE
content-encoding:gzip content-type:application/json Transfer-Encoding:chunked vary:Accept-Encoding
The maximum length of a JSON type using a binary storage format is 16776192 bytes.
An answer to the actual question should include the bytes spent on the headers and should include taking gzip compression into account, but I will ignore those things.
You have a few options. They all output the same answer when run:
If Using a Browser or Node (Not IE)
const size = new TextEncoder().encode(JSON.stringify(obj)).length const kiloBytes = size / 1024; const megaBytes = kiloBytes / 1024;
If you need it to work on IE, you can use a pollyfill
If Using Node
const size = Buffer.byteLength(JSON.stringify(obj))
(which is the same as Buffer.byteLength(JSON.stringify(obj), "utf8")
).
Shortcut That Works in IE, Modern Browsers, and Node
const size = encodeURI(JSON.stringify(obj)).split(/%..|./).length - 1;
That last solution will work in almost every case, but that last solution will throw a URIError: URI malformed
exception if you feed it input containing a string that should not exist, like let obj = { partOfAnEmoji: "👍🏽"[1] }
. The other two solutions I provided will not have that weakness.
(Credits: Credit for the first solution goes here. Credit for the second solution goes to the utf8-byte-length package (which is good, you could use that instead). Most of the credit for that last solution goes to here, but I simplified it a bit. I found the test suite of the utf8-byte-length package super helpful, when researching this.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With