@梁宇轩8年前

02/24
22:59
技术笔记

HTML5 File API小型实用模塊

零、前言

【系統信息】部落格一年不更新成就達成。

其實在暑假的時候我也想過來更新一下部落格,甚至連提綱都寫好了,但是總是會有一些瑣事讓我無法找到時間,來寫一篇博文。

這個模塊是跟隨著一個項目逐漸寫完的,也是隨著需求的深入而逐漸完善。一開始連自定義目錄都不行,而現在已經可以在指定目錄下在多層子文件夾繼續尋找文件了。

一、封裝

考慮到功能性的需要,我選擇了JavaScript中的自定義類型來實現這個模塊。這是因為這個模塊需要儲存一些數據,而且不希望被外部調用,而且也希望可以同時存在兩個或多個這樣的API組來調用不同的內容。

而這個模塊的API設計參考了Chrome Extension的儲存API,但是也不完全一樣。例如這個模塊將文件內需要的內容全部儲存起來,如果文件內容過多的話有可能造成初始化時十分緩慢或者內存佔用過多等。

這個模塊佔用了全局變量Storage還有一點必須注意,由於在前文提到的項目中數據的儲存時key-value的,所以文件內容全部使用JSON格式,而且value的類型都是string,但是get和set的時候會parse和stringify,所以也可以傳入object。

二、初始化

這個是自定義類型的定義:

Storage(directoryRootEntry, map, callback, fail)

這個是初始化的例子:

var storage = new Storage(directoryEntry,{
    'file.json': {
        'key': ['key1', 'key2'],
        'readonly': false
    },
    'subfolder/file.json': {
        'key': ['key3'],
        'readonly': true
    }
}, function(){
    console.info('success');
}, function(error){
    console.error('file error: ' + error.code);
});

其中的directoryEntry是File API中的定義的文件夾物件,將作為各文件的基本文件夾。map是一個key-value表,其中的key是基本文件夾下的相對路徑,value是文件配置,包含兩個屬性,屬性key是一個數組,用來指定哪些key儲存在這個文件裏;屬性readonly是一個布爾量,用來指定這個文件是否只讀。

三、API

  • 獲取數據
var result = storage.get(mission);

get函數獲取一個參數mission,如果是null,則返回整個表;如果是數組,則以key-value的形式返回這個數組裏的全部鍵名和這些鍵名對應的值。

下面是例子:

var result = storage.get(['key1', 'key3']);
  • 寫入數據
storage.set(mission, callback);

set函數獲取兩個參數missioncallbackmission是key-value表,包含要修改的鍵名和對應鍵值;callback是完成時的回調函數。

下面是例子:

storage.set({
    'key1': 'value1',
    'key3': 'value3'
}, function(){
    console.info('success');
});
  • 刪除數據
storage.delete(keys);

delete函數獲取一個參數keys,如果是null,則將所有鍵值置空;如果是數組,則將這個數組裏的全部鍵名各自對應的值置空。

下面是例子:

storage.delete(['key1', 'key3']);

四、相關信息

本模塊已通过Android + PhoneGap環境下的測試。在其他環境下未經測試。

以下是本模塊的源代碼,你也可以點這裡下載:

function Storage(directoryRootEntry, map, callback, fail){
    var cache = {}, tasks = [];
    for(file in map){
        map[file].readonly = (typeof map[file].readonly == 'undefined' ? false : map[file].readonly);
        map[file].lock = false;
        map[file].queue = [];
    }

    function finish(file, mission){
        for(var i = tasks.length - 1; i >= 0; --i){
            if(tasks[i].task[file] == mission){
                delete tasks[i].task[file];

                for(unfinished in tasks[i].task)
                    break;
                setTimeout(tasks[i].callback, 0);
                tasks.splice(i, 1);
                break;
            }
        };

        if(map[file].queue.length == 0)
            map[file].lock = false;
        else
            set(file, map[file].queue.shift());
    }
    function set(file, mission){
        var reader = new FileReader();
        reader.onloadend = function(event){
            var object;
            try{
                object = JSON.parse(event.target.result);
            }
            catch(error){
                object = {};
            }

            for(key in mission)
                object[key] = mission[key];

            var writer = map[file].writer;
            writer.onwriteend = function(event){
                var writer = map[file].writer;
                writer.onwriteend = function(event){
                    finish(file, mission);
                };
                writer.write(JSON.stringify(object));
            }
            writer.truncate(0);
        };
        reader.readAsText(map[file].file);
    }

    this.set = function(mission, callback){
        var task = {};
        for(key in mission){
            for(file in map){
                if(map[file].readonly == true)
                    break;
                for(var i = map[file].key.length - 1; i >= 0; --i)
                    if(map[file].key[i] == key){
                        if(task[file] == undefined)
                            task[file] = {};
                        cache[key] = task[file][key] = mission[key];
                    }
            }
        }
        tasks.push({
            'task': task,
            'callback': callback
        });
        for(file in task){
            if(map[file].lock)
                map[file].queue.push(task[file]);
            else{
                map[file].lock = true;
                set(file, task[file]);
            }
        }
    };
    this.get = function(mission){
        if(mission == null)
            return cache;

        if(typeof mission == 'string')
            mission = [mission];

        result = {};
        for(var i = mission.length - 1; i >= 0; --i)
            result[mission[i]] = cache[mission[i]];
        return result;
    };
    this.delete = function(keys){
        var mission = {};
        if(keys == null)
            for(key in cache)
                mission[key] = {};
        else
            for(var i = keys.length - 1; i >= 0; i--)
                mission[keys[i]] = {};
        this.set(mission);
    };

    var result = {};
    for(path in map)
        result[path] = (map[path].readonly == true ? 1 : 0);
    function report(path){
        result[path] += 1;
        for(path in result)
            if(result[path] < 2)
                return;
        setTimeout(callback, 0);
    }

    for(path in map){
        var getFile = function(directoryEntry, path, file){
            directoryEntry.getFile(file, {create: true, exclusive: false}, function(fileEntry){
                fileEntry.file(function(fileObject){
                    map[path].file = fileObject;

                    var reader = new FileReader();
                    reader.onloadend = function(event){
                        var object;
                        try{
                            object = JSON.parse(event.target.result);
                        }
                        catch(error){
                            object = {};
                        }
                        for(var i = map[path].key.length - 1; i >= 0; --i)
                            cache[map[path].key[i]] = object[map[path].key[i]];

                        report(path);
                    };
                    reader.readAsText(fileObject);
                });
                if(map[path].readonly == false)
                    fileEntry.createWriter(function(writer){
                        map[path].writer = writer;
                        report(path);
                    });
            }, fail);
        };
        var getDirectory = function(directoryEntry, path, array){
            if(array.length == 1)
                return getFile(directoryEntry, path, array[0]);

            directoryEntry.getDirectory(array.shift(), {create: true, exclusive: false}, function(directoryEntry){
                getDirectory(directoryEntry, path, array);
            }, fail);
        };

        getDirectory(directoryRootEntry, path, path.split('/'));
    }
}

本模塊在MIT License的协议下發佈並授權使用。

The MIT License (MIT)
Copyright (c) 2015 LiangYuxuan
Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.

HTML5 File API小型实用模塊