in

How to check the size of local storage using JavaScript | John O’Young | | Jan 2023

0ps8eDoSNdKvjqe D

[ad_1]

Photo by Crystal Jo on Unsplash

Sometimes you want to know the size of the browser’s local storage using JavaScript.

This article shows how to check the size of the browser’s local storage using JavaScript.

You can convert the browser local storage object to a blob and get its size.

To do this, write:

const {
size
} = new Blob(Object.values(localStorage))
console.log(size)

we call Object.values When localStorage Gets an array of local storage values.

then change it to Blob allow constructors to be used size Property for getting the size.

To get the size in kilobytes, write your own function to calculate the number of bytes stored in local storage and convert it to kilobytes.

For example, you can write:

const localStorageSpace = () => {
let allStrings = '';
for (const key of Object.keys(window.localStorage)) {
allStrings += window.localStorage[key];
}
return allStrings ? 3 + ((allStrings.length * 16) / (8 * 1024)) + ' KB' : 'Empty (0 KB)';
};
console.log(localStorageSpace())

define localStorageSpace concatenate all the strings allStrings string.

Then calculate the size by getting length Multiply it by 16.

and it 8 * 1024 Convert to kilobytes.

Add 3 at the end.

You can convert the browser local storage object to a blob and get its size.

To get the size in kilobytes, write your own function to calculate the number of bytes stored in local storage and convert it to kilobytes.

more content PlainEnglish.ioSIGN UP WITH US Free weekly newsletter. Please follow us twitter, LinkedIn, YoutubeWhen discord.

Interested in scaling software startups? check out circuit.



[ad_2]

Source link

What do you think?

Leave a Reply

GIPHY App Key not set. Please check settings

    128374329 mediaitem128374328

    Al-Shabab: US air strike in Somalia 'kills 30 militants'

    128352628 p0dxj3yb

    How eating oysters could help protect the coast