Last active
November 9, 2015 02:03
-
-
Save mohayonao/a1b29ea97b26104ddfd4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var STORAGE = {}; | |
| function createFunctionPromise(func, args) { | |
| return new Promise(function(resolve, reject) { | |
| var data = func.apply(null, args); | |
| if (data instanceof Promise) { | |
| return data.then(resolve, reject); | |
| } | |
| return resolve(data); | |
| }); | |
| } | |
| function createLoadFilePromise(fs, filepath) { | |
| return new Promise(function(resolve, reject) { | |
| fs.readFile(filepath, function(err, data) { | |
| if (err) { | |
| return reject(err); | |
| } | |
| return resolve(data); | |
| }); | |
| }); | |
| } | |
| module.exports = function(fs) { | |
| function register(key, payload) { | |
| if (payload instanceof Promise) { | |
| STORAGE[key] = payload; | |
| } | |
| if (payload instanceof ArrayBuffer || (global.Buffer && payload instanceof global.Buffer)) { | |
| STORAGE[key] = Promise.resolve(payload); | |
| } | |
| if (typeof payload === "function") { | |
| STORAGE[key] = createFunctionPromise(payload, [].slice.call(arguments, 2)); | |
| } | |
| if (typeof payload === "string") { | |
| STORAGE[key] = createLoadFilePromise(fs, payload); | |
| } | |
| } | |
| function unregister(key) { | |
| if (STORAGE.hasOwnProperty(key)) { | |
| delete STORAGE[key]; | |
| } | |
| } | |
| function load(key) { | |
| if (STORAGE.hasOwnProperty(key)) { | |
| return STORAGE[key]; | |
| } | |
| return Promise.reject(new TypeError("NOT FOUND: " + key)); | |
| } | |
| return { register: register, unregister: unregister, load: load }; | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const fs = require("fs"); | |
| const FileStorage = require("file-storage")(fs); | |
| FileStorage.register("a", new Buffer("abc")); | |
| FileStorage.register("b", "./b.txt"); | |
| FileStorage.register("c", loadFromMemcached, "c"); | |
| // | |
| FileStorage.load("a").then((data) => { | |
| assert.deepEqual(data, new Buffer("abc")); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment