rfs.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. function Store(opt){
  2. opt = opt || {};
  3. opt.log = opt.log || console.log;
  4. opt.file = String(opt.file || 'radata');
  5. var fs = require('fs'), u;
  6. var store = function Store(){};
  7. if(Store[opt.file]){
  8. console.log("Warning: reusing same fs store and options as 1st.");
  9. return Store[opt.file];
  10. }
  11. Store[opt.file] = store;
  12. var puts = {};
  13. // TODO!!! ADD ZLIB INFLATE / DEFLATE COMPRESSION!
  14. store.put = function(file, data, cb){
  15. puts[file] = data;
  16. var random = Math.random().toString(36).slice(-3);
  17. var tmp = opt.file+'-'+file+'-'+random+'.tmp';
  18. fs.writeFile(tmp, data, function(err, ok){
  19. delete puts[file];
  20. if(err){ return cb(err) }
  21. move(tmp, opt.file+'/'+file, cb);
  22. });
  23. };
  24. store.get = function(file, cb){ var tmp; // this took 3s+?
  25. if(tmp = puts[file]){ cb(u, tmp); return }
  26. fs.readFile(opt.file+'/'+file, function(err, data){
  27. if(err){
  28. if('ENOENT' === (err.code||'').toUpperCase()){
  29. return cb();
  30. }
  31. opt.log("ERROR:", err);
  32. }
  33. cb(err, data);
  34. });
  35. };
  36. if(!fs.existsSync(opt.file)){ fs.mkdirSync(opt.file) }
  37. function move(oldPath, newPath, cb) {
  38. fs.rename(oldPath, newPath, function (err) {
  39. if (err) {
  40. if (err.code === 'EXDEV') {
  41. var readStream = fs.createReadStream(oldPath);
  42. var writeStream = fs.createWriteStream(newPath);
  43. readStream.on('error', cb);
  44. writeStream.on('error', cb);
  45. readStream.on('close', function () {
  46. fs.unlink(oldPath, cb);
  47. });
  48. readStream.pipe(writeStream);
  49. } else {
  50. cb(err);
  51. }
  52. } else {
  53. cb();
  54. }
  55. });
  56. };
  57. store.list = function(cb, match, params, cbs){
  58. var dir = fs.readdirSync(opt.file);
  59. dir.forEach(function(file){
  60. cb(file);
  61. })
  62. cb();
  63. };
  64. return store;
  65. }
  66. var Gun = (typeof window !== "undefined")? window.Gun : require('../gun');
  67. Gun.on('create', function(root){
  68. this.to.next(root);
  69. var opt = root.opt;
  70. if(opt.rfs === false){ return }
  71. opt.store = opt.store || (!Gun.window && Store(opt));
  72. });
  73. module.exports = Store;