-
-
Save esironal/b8c1c8d0cb8f194f6dba338a0fe04480 to your computer and use it in GitHub Desktop.
simple datastore
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 fs = require('fs'); | |
var localStore = require('./local-store'); | |
var store = new localStore.Store({ | |
path: '/var/data', | |
bucket: 'test' | |
}); | |
var data = fs.readFileSync('/etc/passwd'); | |
store.put('myfile', data, function(err) { | |
if(err) return console.log(err); | |
console.log('file stored'); | |
}); | |
store.get('myfile', function(err, data) { | |
if(err) return console.log(err); | |
console.log(data); | |
}); | |
store.del('myfile', function(err) { | |
if(err) return console.log(err); | |
console.log('file deleted'); | |
}); | |
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 fs = require('fs'); | |
var mkdirp = require('mkdirp'); | |
var crypto = require('crypto'); | |
function Store(options) { | |
this.path = options.path; | |
this.bucket = options.bucket; | |
} | |
Store.prototype._location = function(key) { | |
var hash = crypto.createHash('sha1').update(key).digest('hex'); | |
var dirname = this.path + '/' + this.bucket + '/' + hash.slice(0, 2) + '/' + hash.slice(2, 4); | |
var filename = hash; | |
var fullpath = dirname + '/' + filename; | |
return { | |
dirname: dirname, | |
filename: filename, | |
fullpath: fullpath | |
}; | |
}; | |
Store.prototype.put = function(key, data, callback) { | |
var location = this._location(key); | |
mkdirp(location.dirname, function(err) { | |
if(err) return callback(err); | |
fs.writeFile(location.fullpath, data, callback); | |
}); | |
}; | |
Store.prototype.get = function(key, callback) { | |
var location = this._location(key); | |
fs.readFile(location.fullpath, callback); | |
}; | |
Store.prototype.del = function(key, callback) { | |
var location = this._location(key); | |
fs.unlink(location.fullpath, callback); | |
// TODO: remove directories if empty | |
}; | |
module.exports.Store = Store; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment