UNPKG

dl

Version:

DreamLab Libs

111 lines (88 loc) 3.15 kB
var fs = require('fs'); var Core = require('core'), Class = Core.Class, Assertions = Core.common.Assertions, Types = Core.common.Types; var AbstractDataProvider = require('./AbstractDataProvider.js').AbstractDataProvider; var FileDataProvider = function () { this.Extends = AbstractDataProvider; // this._filePath = null; this.initialize = function (filePath) { Assertions.isString(filePath, FileDataProvider.Exception.BAD_FILE_NAME); this._filePath = filePath; }; this.init = function (callback) { var that = this; fs.stat(this._filePath, function (error, stats) { if (error) { if (error.code != "ENOENT") { callback(error, null); return; } else { fs.writeFile(that._filePath, '', function (error) { if (error) { callback(error, null); return; } callback(null, true); }); } return; } callback(null, true); }); }; this.destroy = function () { this.unwatch(null, function () {}); }; this.watch = function (key, callback) { fs.watchFile(this._filePath, function (current, previous) { if (current.size == 0) { /* * pomijam event przy czyszczeniu pliku * po CLOSE_WRITE zostanie wygenerowany nowy event */ } else { callback(null, current); } }); }; this.unwatch = function (key, callback) { fs.unwatchFile(this._filePath); callback(); }; this.set = function (key, value, callback) { //Assertions.isString(key, FileDataProvider.Exception.KEY_HAS_TO_BE_A_STRING); Assertions.guard(value, [Assertions.isString, Assertions.isObject], FileDataProvider.Exception.WRONG_VALUE); if (Types.isObject(value)) { value = JSON.stringify(value, undefined, 2); } fs.writeFile(this._filePath, value, function (error) { if (error) { callback(error, null); return; } callback(null, true); }); }; this.get = function (key, callback) { fs.readFile(this._filePath, 'utf8', function (error, data) { if (error) { callback(error, null); return; } try { data = JSON.parse(data); } catch (e) { data = {}; } callback(null, data); }); }; }; FileDataProvider = new Class(new FileDataProvider()); FileDataProvider.Exception = {}; FileDataProvider.Exception.BAD_FILE_NAME = "File name has to be a string"; FileDataProvider.Exception.WRONG_KEY = "Key has to be a string"; FileDataProvider.Exception.WRONG_VALUE = "Value has to be a string or an object"; exports.FileDataProvider = FileDataProvider;