|
| 1 | +'use strict' |
| 2 | + |
| 3 | +var IPFS = require('ipfs') |
| 4 | + |
| 5 | +// Create the IPFS node instance |
| 6 | +// for simplicity, we create a new repo everytime the node |
| 7 | +// is created, because you can't init already existing repos |
| 8 | +const repoPath = '' + Math.random() |
| 9 | +const node = new IPFS(repoPath) |
| 10 | +const concat = require('concat-stream') |
| 11 | + |
| 12 | +node.init({ emptyRepo: true, bits: 2048 }, function (err) { |
| 13 | + if (err) { |
| 14 | + throw err |
| 15 | + } |
| 16 | + node.load(function (err) { |
| 17 | + if (err) { |
| 18 | + throw err |
| 19 | + } |
| 20 | + |
| 21 | + node.goOnline(function (err) { |
| 22 | + if (err) { |
| 23 | + throw err |
| 24 | + } |
| 25 | + console.log('IPFS node is ready') |
| 26 | + }) |
| 27 | + }) |
| 28 | +}) |
| 29 | + |
| 30 | +function store () { |
| 31 | + var toStore = document.getElementById('source').value |
| 32 | + |
| 33 | + node.files.add(new Buffer(toStore), function (err, res) { |
| 34 | + if (err || !res) { |
| 35 | + return console.error('ipfs add error', err, res) |
| 36 | + } |
| 37 | + |
| 38 | + res.forEach(function (file) { |
| 39 | + if (file && file.hash) { |
| 40 | + console.log('successfully stored', file.hash) |
| 41 | + display(file.hash) |
| 42 | + } |
| 43 | + }) |
| 44 | + }) |
| 45 | +} |
| 46 | + |
| 47 | +function display (hash) { |
| 48 | + // buffer: true results in the returned result being a buffer rather than a stream |
| 49 | + node.files.cat(hash, function (err, res) { |
| 50 | + if (err || !res) { |
| 51 | + return console.error('ipfs cat error', err, res) |
| 52 | + } |
| 53 | + |
| 54 | + document.getElementById('hash').innerText = hash |
| 55 | + |
| 56 | + res.pipe(concat(function (data) { |
| 57 | + document.getElementById('content').innerText = data |
| 58 | + })) |
| 59 | + }) |
| 60 | +} |
| 61 | + |
| 62 | +document.addEventListener('DOMContentLoaded', function () { |
| 63 | + document.getElementById('store').onclick = store |
| 64 | +}) |
0 commit comments