sourcetip

localStorage의 크기를 찾는 방법

fileupload 2023. 10. 20. 14:08
반응형

localStorage의 크기를 찾는 방법

현재 HTML5의 로컬 스토리지를 활용할 수 있는 사이트를 개발 중입니다.브라우저별 크기 제한에 대해서 다 읽어봤습니다.그러나 로컬 스토리지 인스턴스의 현재 크기를 확인하는 방법에 대해서는 아무것도 보지 못했습니다.질문은 자바스크립트에 주어진 변수의 크기를 보여주는 내장된 방식이 없다는 것을 나타내는 것 같습니다.localStorage에 내가 보지 못한 메모리 크기 속성이 있습니까?제가 놓치고 있는 쉬운 방법이 있을까요?

제 사이트는 사용자가 '오프라인' 모드로 정보를 입력할 수 있도록 하기 위한 것이므로, 저장 공간이 거의 가득 찼을 때 경고를 줄 수 있는 것은 매우 중요합니다.

자바스크립트 콘솔(한 줄 버전)에서 이 토막글을 실행합니다.

var _lsTotal=0,_xLen,_x;for(_x in localStorage){ if(!localStorage.hasOwnProperty(_x)){continue;} _xLen= ((localStorage[_x].length + _x.length)* 2);_lsTotal+=_xLen; console.log(_x.substr(0,50)+" = "+ (_xLen/1024).toFixed(2)+" KB")};console.log("Total = " + (_lsTotal / 1024).toFixed(2) + " KB");


읽기 위해 여러 줄로 동일한 코드를 사용합니다.

var _lsTotal = 0,
    _xLen, _x;
for (_x in localStorage) {
    if (!localStorage.hasOwnProperty(_x)) {
        continue;
    }
    _xLen = ((localStorage[_x].length + _x.length) * 2);
    _lsTotal += _xLen;
    console.log(_x.substr(0, 50) + " = " + (_xLen / 1024).toFixed(2) + " KB")
};
console.log("Total = " + (_lsTotal / 1024).toFixed(2) + " KB");

또는 편리하게 사용하기 위해 책갈피의 '위치' 필드에 이 텍스트를 추가합니다.

javascript: var x, xLen, log=[],total=0;for (x in localStorage){if(!localStorage.hasOwnProperty(x)){continue;} xLen =  ((localStorage[x].length * 2 + x.length * 2)/1024); log.push(x.substr(0,30) + " = " +  xLen.toFixed(2) + " KB"); total+= xLen}; if (total > 1024){log.unshift("Total = " + (total/1024).toFixed(2)+ " MB");}else{log.unshift("Total = " + total.toFixed(2)+ " KB");}; alert(log.join("\n")); 

추신: 의견 요청에 따라 토막글이 업데이트됩니다.이제 계산에는 키 자체의 길이가 포함됩니다.charin javascript는 UTF-16으로 저장하기 때문에 각각의 길이에 2를 곱합니다(2바이트를 차지합니다).

추신. Chrome과 Firefox에서 모두 작동해야 합니다.

@Shourav가 위에서 말한 것에서 벗어나, 나는 당신의 모든 것을 정확하게 잡을 수 있는 작은 함수를 썼습니다.localStorage(현재 도메인에 대한) 키와 결합된 크기를 계산하여 사용자가 사용하는 메모리의 양을 정확하게 알 수 있습니다.localStorage개체:

var localStorageSpace = function(){
        var allStrings = '';
        for(var key in window.localStorage){
            if(window.localStorage.hasOwnProperty(key)){
                allStrings += window.localStorage[key];
            }
        }
        return allStrings ? 3 + ((allStrings.length*16)/(8*1024)) + ' KB' : 'Empty (0 KB)';
    };

반환된 내 것:"30.896484375 KB"

Blob 기능을 사용하면 로컬 스토리지 데이터의 현재 크기를 얻을 수 있습니다.이 기능은 이전 브라우저에서는 작동하지 않을 수 있습니다. 지원 기능 및 캐니유저를 확인하십시오.

예:

return new Blob(Object.values(localStorage)).size;

Object.values()는 localStorage 개체를 배열로 바꿉니다.Blob은 배열을 원시 데이터로 바꿉니다.

IE에는 Storage 개체의 Space 속성이 남아 있습니다.현재 다른 브라우저에는 이와 동등한 브라우저가 없습니다.

개인적으로 테스트를 해본 적은 없지만 기본 공간은 5MB로 알고 있습니다.

다음은 이 방법의 간단한 예이며 모든 브라우저에서 작동해야 합니다.

alert(1024 * 1024 * 5 - unescape(encodeURIComponent(JSON.stringify(localStorage))).length);

누군가에게 도움이 되길 바랍니다.

jsfiddle의 jas-예문은 저에게 통하지 않기 때문에 저는 이 해결책을 생각해 냈습니다.(아래 코드에서 사용한 Serge Selletskyy와 Shourav의 비트에 감사드립니다.)

아래는 localStorage에 사용할 수 있는 공간과 (이미 lS에 있는 키가 있는 경우) 남아 있는 공간을 테스트하는 데 사용할 수 있는 기능입니다.

이것은 아주 작은 힘이지만 파이어폭스를 제외한 거의 모든 브라우저에서 작동합니다.데스크톱 FF에서는 완료하는 데 4-5분이 걸리고 Android에서는 충돌만 발생합니다.

이 기능 아래에는 여러 플랫폼의 다른 브라우저에서 수행한 테스트에 대한 간단한 요약이 있습니다.맛있게 드세요.

function testLocalStorage() {
    var timeStart = Date.now();
    var timeEnd, countKey, countValue, amountLeft, itemLength;
    var occupied = leftCount = 3; //Shurav's comment on initial overhead
//create localStorage entries until localStorage is totally filled and browser issues a warning.
    var i = 0;
    while (!error) {
        try {
//length of the 'value' was picked to be a compromise between speed and accuracy, 
// the longer the 'value' the quicker script and result less accurate. This one is around 2Kb 
            localStorage.setItem('testKey' + i, '11111111112222222222333333333344444444445555555555666661111111111222222222233333333334444444444555555555566666');
        } catch (e) {
            var error = e;
        }
        i++;
    }
//if the warning was issued - localStorage is full.
    if (error) {
//iterate through all keys and values to count their length
        for (var i = 0; i < localStorage.length; i++) {
            countKey = localStorage.key(i);
            countValue = localStorage.getItem(localStorage.key(i));
            itemLength = countKey.length + countValue.length;
//if the key is one of our 'test' keys count it separately
            if (countKey.indexOf("testKey") !== -1) {
                leftCount = leftCount + itemLength;
            }
//count all keys and their values
            occupied = occupied + itemLength;
        }
        ;
//all keys + values lenght recalculated to Mb
        occupied = (((occupied * 16) / (8 * 1024)) / 1024).toFixed(2);
//if there are any other keys then our 'testKeys' it will show how much localStorage is left
        amountLeft = occupied - (((leftCount * 16) / (8 * 1024)) / 1024).toFixed(2);
//iterate through all localStorage keys and remove 'testKeys'
        Object.keys(localStorage).forEach(function(key) {
            if (key.indexOf("testKey") !== -1) {
                localStorage.removeItem(key);
            }
        });

    }
//calculate execution time
    var timeEnd = Date.now();
    var time = timeEnd - timeStart;
//create message
    var message = 'Finished in: ' + time + 'ms \n total localStorage: ' + occupied + 'Mb \n localStorage left: ' + amountLeft + "Mb";
//put the message on the screen
    document.getElementById('scene').innerText = message; //this works with Chrome,Safari, Opera, IE
//document.getElementById('scene').textContent = message;  //Required for Firefox to show messages
}

그리고 다른 브라우저에서의 몇 가지 테스트 위에서 약속했듯이:

갤럭시탭 10.1

  • 맥스톤패드 1.7~1130ms 5Mb
  • 파이어폭스 20.0(베타 20.0)이 둘 다 충돌했습니다.
  • 크롬 25.0.1364.169~22250ms/5Mb
  • 네이티브(Safari 4.0/Webkit534로 식별됨).30) ~995ms/5Mb

아이폰4s iOS 6.1.3

  • 사파리 ~ 520ms/5Mb
  • As HomeApp ~525ms/5Mb
  • iCab ~ 710ms/5mb

MacBook Pro OSX 1.8.3 (Core 2 Duo 2.66 8Gb 메모리)

  • 사파리 6.0.3 ~105ms/5Mb
  • 크롬 26.0.1410.43 ~3400ms/5Mb
  • Firefox 20.00 300150ms(!)/10Mb (스크립트가 너무 오래 실행된다는 불만이 제기된 후)

아이패드3 iOS 6.1.3

  • 사파리 ~430ms/5Mb
  • iCab ~595ms/5mb

Windows 7 - 64b (Core 2 Duo 2.936Gb 메모리)

  • 사파리 5.1.7~80ms/5Mb
  • 크롬 26.0.1410.43 ~1220ms/5Mb
  • Firefox 20.0 228500ms(!) / 10Mb (스크립트가 너무 오래 실행된다는 불만이 제기된 후)
  • IE9 ~ 17900ms/9.54Mb (console.logs가 코드에 있는 경우 DevTools가 열릴 때까지 작동하지 않음)
  • Opera 12.15 ~4212ms / 3.55Mb (5Mb를 선택한 경우인데, Opera에서 lS의 양을 늘리려고 하는지 친절하게 묻습니다. 안타깝게도 몇 번 연속 테스트를 진행하면 충돌합니다.)

우승 8 (병렬 8 아래)

  • IE10 ~7850ms/9.54Mb

로컬 스토리지는 다음과 같은 방법으로 계산할 수 있습니다.

function sizeofAllStorage(){  // provide the size in bytes of the data currently stored
  var size = 0;
  for (i=0; i<=localStorage.length-1; i++)  
  {  
  key = localStorage.key(i);  
  size += lengthInUtf8Bytes(localStorage.getItem(key));
  }  
  return size;
}

function lengthInUtf8Bytes(str) {
  // Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
  var m = encodeURIComponent(str).match(/%[89ABab]/g);
  return str.length + (m ? m.length : 0);
}

console.log(sizeofAllStorage());

최종 크기(바이트)가 브라우저에 기록됩니다.

저는 @tennisgen의 코드를 사용해서 모든 것을 얻고 내용을 세지만, 키 자체를 셉니다.

var localStorageSpace = function(){
        var allStrings = '';
        for(var key in window.localStorage){
            allStrings += key;
            if(window.localStorage.hasOwnProperty(key)){
                allStrings += window.localStorage[key];
            }
        }
        return allStrings ? 3 + ((allStrings.length*16)/(8*1024)) + ' KB' : 'Empty (0 KB)';
    };

제가 이 문제를 해결한 방법은 Local Storage에서 사용된 공간과 남아있는 공간을 찾는 함수를 만들고 그 함수를 호출하여 최대 저장 공간을 결정하는 함수를 만드는 것입니다.

function getUsedSpaceOfLocalStorageInBytes() {
    // Returns the total number of used space (in Bytes) of the Local Storage
    var b = 0;
    for (var key in window.localStorage) {
        if (window.localStorage.hasOwnProperty(key)) {
            b += key.length + localStorage.getItem(key).length;
        }
    }
    return b;
}

function getUnusedSpaceOfLocalStorageInBytes() {
    var maxByteSize = 10485760; // 10MB
    var minByteSize = 0;
    var tryByteSize = 0;
    var testQuotaKey = 'testQuota';
    var timeout = 20000;
    var startTime = new Date().getTime();
    var unusedSpace = 0;
    do {
        runtime = new Date().getTime() - startTime;
        try {
            tryByteSize = Math.floor((maxByteSize + minByteSize) / 2);
            //localStorage.setItem(testQuotaKey, new Array(tryByteSize).join('1'));
            
            //Recommended by @pkExec and @jrob007
            localStorage.setItem(testQuotaKey, String('1').repeat(tryByteSize));
            minByteSize = tryByteSize;
        } catch (e) {
            maxByteSize = tryByteSize - 1;
        }
    } while ((maxByteSize - minByteSize > 1) && runtime < timeout);

    localStorage.removeItem(testQuotaKey);

    if (runtime >= timeout) {
        console.log("Unused space calculation may be off due to timeout.");
    }

    // Compensate for the byte size of the key that was used, then subtract 1 byte because the last value of the tryByteSize threw the exception
    unusedSpace = tryByteSize + testQuotaKey.length - 1;
    return unusedSpace;
}

function getLocalStorageQuotaInBytes() {
    // Returns the total Bytes of Local Storage Space that the browser supports
    var unused = getUnusedSpaceOfLocalStorageInBytes();
    var used = getUsedSpaceOfLocalStorageInBytes();
    var quota = unused + used;
    return quota;
}

여기서 가장 많이 투표된 @serge의 답변 외에 키의 크기도 고려해야 합니다.아래 코드에 저장된 키의 크기가 추가됩니다.localStorage

var t = 0; 
for (var x in localStorage) { 
    t += (x.length + localStorage[x].length) * 2; 
} 
console.log((t / 1024) + " KB");

사양에 따라 문자열의 각 문자는 16비트입니다.

그러나 크롬(Settings > Content Settings > Cookies & Site data)으로 검사하면 로컬 스토리지를 시작하는 데 3kB(오버헤드 크기)가 소요됨을 알 수 있습니다.

저장된 데이터 크기는 이 관계식을 따릅니다(정확하게는 1kB).
3 + ((localStorage.x.length*16)/(8*1024)) kB

localStorage.x는 저장 문자열입니다.

네, 이 질문은 10년 전쯤에 한 질문입니다.하지만 관심이 있는 사람들(저처럼 로컬 스토리지로 데이터를 저장하는 오프라인 텍스트 편집기를 만들고 있기 때문에)은 다음과 같은 간단한 것을 사용할 수 있습니다.

var warning = 1;
var limit = 2000000; //2 million characters, not really taking in account to bytes but for tested number of characters stored
setInterval(function() {
    localStorage["text"] = document.getElementById("editor").innerHTML; //gets text and saves it in local storage under "text"
    if(localStorage["text"].length > limit && warning == 1){
            alert("Local Storage capacity has been filled"); 
            warning = 2; //prevent a stream of alerts
    }
}, 1000);
//setInterval function saves and checks local storage

저장 용량을 채우는 가장 좋은 방법은 사이트 설정(예: 로컬 저장소에 이미지를 저장한 경우)을 보는 것입니다.적어도 크롬에서는 사용된 바이트의 양(즉, 1222바이트)을 볼 수 있습니다.그러나 js로 채워진 로컬 스토리지를 볼 수 있는 가장 좋은 방법은 위에서 이미 언급했으므로 이를 사용합니다.

//메모리는 키와 값이 모두 차지하므로 업데이트된 코드입니다.

var jsonarr=[];
var jobj=null;
for(x in sessionStorage) // Iterate through each session key
{
    jobj={}; 
    jobj[x]=sessionStorage.getItem(x); //because key will also occupy some memory
    jsonarr.push(jobj);
    jobj=null;
}
//https://developer.mozilla.org/en/docs/Web/JavaScript/Data_structures 
//JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. 
var size=JSON.stringify(jsonarr).length*2; //16-bit that's why multiply by 2
var arr=["bytes","KB","MB","GB","TB"]; // Define Units
var sizeUnit=0;
while(size>1024){ // To get result in Proper Unit
    sizeUnit++;
    size/=1024;
}
alert(size.toFixed(2)+" "+arr[sizeUnit]);

페이지가 로드된 후 또는 다음과 같은 입력 포커스에서 테스트 내용을 사용하여 시도/캐치를 수행합니다.

function canSetItem(){
    const KEY = "check_available_space"
    try {
        localStorage.setItem(KEY, KEY);
    } catch(e) {
        console.error(e);
        return false;
    }
    localStorage.removeItem(KEY);
    return true;
}
window.localStorage.remainingSpace

언급URL : https://stackoverflow.com/questions/4391575/how-to-find-the-size-of-localstorage

반응형