1
0
Fork 0
mirror of https://github.com/SunRed/haste-server.git synced 2024-11-24 02:00:17 +01:00
haste-server/lib/document_stores/file.js

64 lines
1.5 KiB
JavaScript
Raw Normal View History

2020-08-26 04:54:58 +02:00
const fs = require('fs');
const crypto = require('crypto');
2011-11-18 23:54:57 +01:00
2020-08-26 04:54:58 +02:00
const winston = require('winston');
2011-11-18 23:54:57 +01:00
// For storing in files
2011-11-22 04:03:50 +01:00
// options[type] = file
// options[path] - Where to store
2011-11-18 23:54:57 +01:00
2020-08-28 04:39:03 +02:00
const FileDocumentStore = function(options){
this.basePath = options.path || './data';
this.expire = options.expire;
2011-11-18 23:54:57 +01:00
};
// Generate md5 of a string
2020-08-28 04:39:03 +02:00
FileDocumentStore.md5 = function(str){
let md5sum = crypto.createHash('md5');
md5sum.update(str);
return md5sum.digest('hex');
};
// Save data in a file, key as md5 - since we don't know what we could
// be passed here
2020-08-28 04:39:03 +02:00
FileDocumentStore.prototype.set = function(key, data, callback, skipExpire){
try {
const _this = this;
fs.mkdir(this.basePath, '700', function(){
const fn = _this.basePath + '/' + FileDocumentStore.md5(key);
fs.writeFile(fn, data, 'utf8', function(err){
if (err){
callback(false);
}
else {
callback(true);
if (_this.expire && !skipExpire){
winston.warn('file store cannot set expirations on keys');
}
}
});
});
} catch(err){
callback(false);
}
2011-11-18 23:54:57 +01:00
};
// Get data from a file from key
2020-08-28 04:39:03 +02:00
FileDocumentStore.prototype.get = function(key, callback, skipExpire){
const _this = this;
const fn = require('path').join(this.basePath, FileDocumentStore.md5(key));
fs.readFile(fn, 'utf8', function(err, data){
if (err){
callback(false);
}
else {
callback(data);
if (_this.expire && !skipExpire){
winston.warn('file store cannot set expirations on keys');
}
}
});
2011-11-18 23:54:57 +01:00
};
module.exports = FileDocumentStore;