rfs.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. var Gun = (typeof window !== "undefined")? window.Gun : require('../gun');
  2. function Store(opt){
  3. opt = opt || {};
  4. opt.file = String(opt.file || 'radata');
  5. var fs = require('fs'), u;
  6. var store = function Store(){};
  7. store.put = function(file, data, cb){
  8. var random = Math.random().toString(36).slice(-3);
  9. var tmp = opt.file+'-'+file+'-'+random+'.tmp';
  10. fs.writeFile(tmp, data, function(err, ok){
  11. if(err){ return cb(err) }
  12. move(tmp, opt.file+'/'+file, cb);
  13. });
  14. };
  15. store.get = function(file, cb){
  16. fs.readFile(opt.file+'/'+file, function(err, data){
  17. if(err){
  18. if('ENOENT' === (err.code||'').toUpperCase()){
  19. return cb(null);
  20. }
  21. Gun.log("ERROR:", err)
  22. }
  23. cb(err, data);
  24. });
  25. };
  26. store.list = function(cb, match){
  27. fs.readdir(opt.file, function(err, dir){
  28. Gun.obj.map(dir, cb) || cb(); // Stream interface requires a final call to know when to be done.
  29. });
  30. };
  31. if(!fs.existsSync(opt.file)){ fs.mkdirSync(opt.file) }
  32. //store.list(function(){ return true });
  33. function move(oldPath, newPath, cb) {
  34. fs.rename(oldPath, newPath, function (err) {
  35. if (err) {
  36. if (err.code === 'EXDEV') {
  37. var readStream = fs.createReadStream(oldPath);
  38. var writeStream = fs.createWriteStream(newPath);
  39. readStream.on('error', cb);
  40. writeStream.on('error', cb);
  41. readStream.on('close', function () {
  42. fs.unlink(oldPath, cb);
  43. });
  44. readStream.pipe(writeStream);
  45. } else {
  46. cb(err);
  47. }
  48. } else {
  49. cb();
  50. }
  51. });
  52. };
  53. return store;
  54. }
  55. function Mem(opt){
  56. opt = opt || {};
  57. opt.file = String(opt.file || 'radata');
  58. var storage = Mem.storage || (Mem.storage = {});
  59. var store = function Store(){}, u;
  60. store.put = function(file, data, cb){
  61. setTimeout(function(){
  62. storage[file] = data;
  63. cb(null, 1);
  64. }, 1);
  65. };
  66. store.get = function(file, cb){
  67. setTimeout(function(){
  68. var tmp = storage[file] || u;
  69. cb(null, tmp);
  70. }, 1);
  71. };
  72. store.list = function(cb, match){
  73. setTimeout(function(){
  74. Gun.obj.map(Object.keys(storage), cb) || cb();
  75. }, 1);
  76. };
  77. return store;
  78. }
  79. module.exports = Store;//Gun.TESTING? Mem : Store;