Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I estimate the disk size of a string with JavaScript?

I need to try to estimate the DISK size of a text string (which could be raw text or a Base64 encoded string for an image/audio/etc) in JavaScript. I'm not sure how to estimate this. The only thing when Googling i can find is .length so i thought maybe someone on StackOverflow might know...

The reason i need to know is i have a localStorage script that needs (or would love to have) the ability to check when a user is nearing his 5MB (or 10MB in IE) quota and prompt them to increase the max size for the domain. So, if a user hits, lets say, 4.5MBs of data it'd prompt with

You're nearing your browsers 5MB data cap. Please increase your max data by... [instructions on increasing it for the browser]

like image 664
Oscar Godson Avatar asked Nov 29 '10 22:11

Oscar Godson


1 Answers

It is going to depend on your character encoding. If you use ASCII encoding, it's going to be str.length bytes. If you use UTF-16, it's going to be (str.length * 2) bytes. If you use UTF-8, it is going to depend on the characters in the string. (Some characters will only take 1 byte, but others could take up to 4 bytes.) If you're dealing with Base64-encoded data, the characters are all within the ASCII range and therefore would occupy str.length bytes on disk. If you decode them first and save as binary, it would take (str.length * 3/4) bytes. (With Base64, 3 uncoded bytes become 4 coded bytes.)

BTW - If you haven't read Joel Spolsky's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!), you should do so immediately.

http://www.joelonsoftware.com/articles/Unicode.html

UPDATE: If you're using localStorage, I assume that you're familiar with window.localStorage.length, though this only tells you how much has been used, not whether your new data will fit. I would also highly recommend reading Dive into HTML5, especially the section on storage:

http://diveintohtml5.ep.io/storage.html

Unless something has changed since its writing, I'm not sure what you can do as localStorage limits you to 5MB per domain with no way for the user to increase it.

like image 198
James Kovacs Avatar answered Oct 10 '22 22:10

James Kovacs