|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const fs = require('fs') |
| 4 | +const os = require('os') |
| 5 | +const path = require('path') |
| 6 | +const promisify = require('promisify-es6') |
| 7 | +// const IPFS = require('../../src/core') |
| 8 | +// replace this by line below if you are using ipfs as a dependency of your |
| 9 | +// project |
| 10 | +const IPFS = require('ipfs') |
| 11 | + |
| 12 | +/* |
| 13 | + * Create a new IPFS instance, using default repo (fs) on default path (~/.ipfs) |
| 14 | + */ |
| 15 | +const node = new IPFS({ |
| 16 | + repo: path.join(os.tmpdir() + '/' + new Date().toString()), |
| 17 | + init: false, |
| 18 | + start: false, |
| 19 | + EXPERIMENTAL: { |
| 20 | + pubsub: false |
| 21 | + } |
| 22 | +}) |
| 23 | + |
| 24 | +const fileToAdd = { |
| 25 | + path: 'hello.txt', |
| 26 | + content: fs.createReadStream('./hello.txt') |
| 27 | +} |
| 28 | + |
| 29 | +/* |
| 30 | + * Display version of js-ipfs |
| 31 | + */ |
| 32 | +node.version() |
| 33 | + .then((version) => { |
| 34 | + console.log('IPFS Version:', version.version) |
| 35 | + return Promise.resolve() |
| 36 | + }) |
| 37 | + |
| 38 | + /* |
| 39 | + * Initialize the repo for this node |
| 40 | + */ |
| 41 | + .then(() => { |
| 42 | + // we need to promisify node.init to return a promise |
| 43 | + return promisify(node.init)({ emptyRepo: true, bits: 2048 }) |
| 44 | + }) |
| 45 | + |
| 46 | + /* |
| 47 | + * Take the node online (bitswap, network and so on) |
| 48 | + */ |
| 49 | + .then(() => { |
| 50 | + // we need to promisify node.start to return a promise |
| 51 | + return promisify(node.start)() |
| 52 | + }) |
| 53 | + |
| 54 | + /* |
| 55 | + * Add a file to IPFS - Complete Files API on: |
| 56 | + * https://github.com/ipfs/interface-ipfs-core/tree/master/API/files |
| 57 | + */ |
| 58 | + .then(() => { |
| 59 | + if (node.isOnline()) { |
| 60 | + console.log('\nNode is now ready and online') |
| 61 | + } |
| 62 | + return node.files.add(fileToAdd) |
| 63 | + }) |
| 64 | + |
| 65 | + .then((result) => { |
| 66 | + let file = result[0] |
| 67 | + console.log('\nAdded file:') |
| 68 | + console.log(file) |
| 69 | + let fileMultihash = file.hash |
| 70 | + return Promise.resolve(fileMultihash) |
| 71 | + }) |
| 72 | + |
| 73 | + /* |
| 74 | + * Awesome we've added a file so let's retrieve and |
| 75 | + * display its contents from IPFS |
| 76 | + */ |
| 77 | + .then((fileMultihash) => { |
| 78 | + return node.files.cat(fileMultihash) |
| 79 | + }) |
| 80 | + |
| 81 | + .then((stream) => { |
| 82 | + console.log('\nFile content:') |
| 83 | + stream.pipe(process.stdout) |
| 84 | + stream.on('end', process.exit) |
| 85 | + return Promise.resolve() |
| 86 | + }) |
| 87 | + |
| 88 | + .then(() => { |
| 89 | + console.log('Success!') |
| 90 | + }) |
| 91 | + |
| 92 | + .catch((err) => { |
| 93 | + console.log(err) |
| 94 | + }) |
0 commit comments