HTML5 localStorage を File っぽく使えるようにしてみた
HTML5 localStorage を File っぽく使えるクラスを作ってみました.
名前は WebFile. 使用方法は Python の File クラスに似ています.
SAMPLE And DATA
サンプルはこちらで遊ぶことができます.
WebFile を使って作ったサンプルプログラムです.
save ボタンを押すとテキストエリアの内容を保存します. また再度このページを開いた際に以前セーブした内容をテキストエリアに表示します. test ボタンを押すと WebFile の動作確認用のテストプログラムが走ります.
データはここからダウンロードできます
CODE
tm.webfile.js
WebFile クラス全体のコードです.
var tm = tm || {}; tm.WebFile = (function() { var temp_class = function() { this.init.apply(this, arguments); return this; }; temp_class.prototype = { name: null, type: null, data: null, init: function(name, type) { if (arguments.length > 0) { this.open.apply(this, arguments); } return this; }, open: function(name, type) { type = type || 'r'; this.name = name; this.type = type; switch ( this.type ) { case 'r' : this.data = localStorage.getItem(name) || ""; break; case 'w' : this.data = ""; break; } return this; }, close: function() { switch ( this.type ) { case 'r' : break; case 'w' : localStorage.setItem(this.name, this.data); break; } this.name = ""; this.type = ""; this.data = null; return this; }, write: function(str) { if (this.type != 'w') { alert("error: read only"); return ; } this.data += str; return this; }, writeLines: function(strs) { if (this.type != 'w') { alert("error: read only"); return ; } for (var i=0; i<strs.length; ++i) { this.data += strs[i] + '\n'; } return this; }, read: function() { return this.data; }, readLines: function() { return this.data.split('\n'); } }; return temp_class; })();
Test Program
動作確認用のテストプログラムです.
tm.WebFile.test = function(){ // write test (function(){ var file = new tm.WebFile("test.txt", 'w'); file.write("Test\n"); file.writeLines(["Test0", "Test1", "Test2"]); file.close(); })(); // read test (function(){ var file = new tm.WebFile("test.txt", 'r'); var data = file.read(); alert(data); var lines = file.readLines(); alert(lines); file.close(); })(); // error test (function(){ var file = new tm.WebFile("test.txt", 'r'); file.write("test"); file.writeLines(["test", "test", "test"]) file.close(); })(); };
Sample
サンプルで WebFile を使用している部分です.
var $id = function(id) { return document.getElementById(id); } var $class = function(c, i){ i=i||0; return document.getElementsByClassName(c)[i]; } var $classes= function(c) { return document.getElementsByClassName(c); } var saveFile = function(){ // データ取得 var name = $id("file-name").innerHTML; var data = $id("main-ta").value; // 書き込み専用としてファイルを開く var file = new tm.WebFile(name, 'w'); file.write(data); file.close(); alert("テキストエリアの内容を保存しました."); }; var openFile = function(){ var name = $id("file-name").innerHTML; // 読み込み専用としてファイルを開く var file = new tm.WebFile(name, 'r'); $id("main-ta").value = file.read(); file.close(); }; window.addEventListener("load", function(){ openFile(); }, false);
現在, 丁度1年前に作った WebEditor を改良中. 近々公開予定.
HTML5