IndexedDB has no built-in mechanism for calculating the size of a database. Below is a code snippet that shows how to calculate the ‘approximate’ size if you are storing strings. In my case we are storing Base64 images.
Depending on what data type you are storing here are some suggestions on how to calculate the size:
- String. The example shown below simply uses the String.length property. You can typically get a one-to-one ratio where each character is equal to one byte. For example, if length equals 20, you can roughly assume that the size of the string is 20 bytes. However, if you have many uncommon characters in your strings those can equal 2 bytes each. For more information see this page on the Mozilla Developer Network.
- Array. The size of an array depends on the array type and what you are storing in it. If it’s just a plain old Array of strings, such as [“a”,”test”,”something”], you can parse the array for strings and then measure the size of each item within it as I just mentioned. If it’s a typed array you’ll have to take into account if it’s 8-bit, 16-bit, 32-bit or 64-bit. If you have numbers in your array, I believe all JavaScript numbers are 8 bytes each.
- Blob. Access the Blob.size property.
/** * Provides the size of database in bytes * @param callback callback(size, null) or callback(null, error) */ var size = function(callback){ if(this._db != null){ var size = 0; var transaction = this._db.transaction(["your_db"]) .objectStore("your_db") .openCursor(); transaction.onsuccess = function(event){ var cursor = event.target.result; if(cursor){ var storedObject = cursor.value; var json = JSON.stringify(storedObject); size += json.length; cursor.continue(); } else{ callback(size,null); } }.bind(this); transaction.onerror = function(err){ callback(null,err); } } else{ callback(null,null); } }
Usage
Here’s how you would use this in your application:
getSize(function(size,err){ if(size > 0){ console.log("Database size = " + size + " bytes"); } if(err != null){ console.log("There was a problem getting database size: " + err); } }
Reference
Hi there,
What is the “this._db”?
@yorkay, the ‘this’ keyword is a reference to the current object. To make things confusing the current object isn’t always what you expect it to be. Here’s a blog post that might help: http://www.moreofless.co.uk/javascript-this-scope-usage/
@yorkay, if you have a single page application with all the JavaScript inline, you wouldn’t need to use the ‘this’ keyword. You would simply be able to refer to the database variable directly: e.g. var _db = …