ipfs.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. console.log("IPFS PLUGIN NOT OFFICIALLY MAINTAINED! PROBABLY WON'T WORK! USE AT YOUR OWN RISK! PLEASE CONTRIBUTE FIXES!");
  2. var opt = gun._.opt, u;
  3. if (u === opt.ipfs.directory) {
  4. opt.ipfs.directory = '/gun';
  5. }
  6. opt.store = {};
  7. opt.store.put = function(file, data, cb){
  8. var uri = opt.ipfs.directory + '/' + file;
  9. opt.ipfs.instance.files.write(uri, Buffer.from(JSON.stringify(data)), {create:true})
  10. .then(res => {
  11. console.log('File written to IPFS directory', uri, res);
  12. return opt.ipfs.instance.files.stat(opt.ipfs.directory, {hash:true});
  13. }).then(res => {
  14. console.log('Directory hash:', res.hash);
  15. return opt.ipfs.instance.name.publish(res.hash);
  16. // currently throws "This command must be run in online mode. Try running 'ipfs daemon' first." for some reason, maybe js-ipfs IPNS not ready yet
  17. }).then(res => {
  18. console.log('IPFS put request successful:', res);
  19. cb(undefined, 1);
  20. }).catch(error => {
  21. console.error('IPFS put request failed', error);
  22. });
  23. }
  24. opt.store.get = function(file, cb){
  25. var uri = opt.ipfs.directory + '/' + file;
  26. opt.ipfs.instance.files.read(uri, {})
  27. .then(res => {
  28. var data = JSON.parse(res.toString());
  29. console.log(uri + ' was loaded from ipfs:', data);
  30. cb(data);
  31. });
  32. }
  33. opt.store.list = function(cb){
  34. var stream = opt.ipfs.files.lsReadableStream(opt.ipfs.directory);
  35. stream.on('data', (file) => {
  36. console.log('ls', file.name);
  37. if (cb(file.name)) {
  38. stream.destroy();
  39. }
  40. });
  41. stream.on('finish', () => {
  42. cb();
  43. });
  44. }