Skip to content

Commit 329faaf

Browse files
author
Alan Shaw
authored
docs: update examples (ipfs#2319)
Since I was going through these anyway to ensure they work with [0.37](ipfs#2192) I've updated the examples to use the new [`IPFS.create` constructor](https://github.com/ipfs/js-ipfs#ipfs-constructor) and switched to using the promised API so that we onboard new users to using promises and minimise the disruption caused when ipfs#1670 bubbles up to here. License: MIT Signed-off-by: Alan Shaw <alan.shaw@protocol.ai>
1 parent 3949a87 commit 329faaf

File tree

34 files changed

+577
-734
lines changed

34 files changed

+577
-734
lines changed

examples/browser-add-readable-stream/index.js

+21-28
Original file line numberDiff line numberDiff line change
@@ -3,39 +3,27 @@
33
/* global Ipfs */
44
/* eslint-env browser */
55

6-
const repoPath = `ipfs-${Math.random()}`
7-
const ipfs = new Ipfs({ repo: repoPath })
86
const { Buffer } = Ipfs
97

10-
ipfs.on('ready', () => {
11-
const directory = 'directory'
8+
const main = async () => {
9+
const repoPath = `ipfs-${Math.random()}`
10+
const ipfs = await Ipfs.create({ repo: repoPath })
1211

13-
// Our list of files
14-
const files = createFiles(directory)
15-
16-
streamFiles(directory, files, (err, directoryHash) => {
17-
if (err) {
18-
return log(`There was an error adding the files ${err}`)
19-
}
12+
const directoryName = 'directory'
2013

21-
ipfs.ls(directoryHash, (err, files) => {
22-
if (err) {
23-
return log(`There was an error listing the files ${err}`)
24-
}
14+
// Our list of files
15+
const inputFiles = createFiles(directoryName)
2516

26-
log(`
27-
--
17+
const directoryHash = await streamFiles(ipfs, directoryName, inputFiles)
2818

29-
Directory contents:
19+
const fileList = await ipfs.ls(directoryHash)
3020

31-
${directory}/ ${directoryHash}`)
21+
log(`\n--\n\nDirectory contents:\n\n${directoryName}/ ${directoryHash}`)
3222

33-
files.forEach((file, index) => {
34-
log(` ${index < files.length - 1 ? '\u251C' : '\u2514'}\u2500 ${file.name} ${file.path} ${file.hash}`)
35-
})
36-
})
23+
fileList.forEach((file, index) => {
24+
log(` ${index < fileList.length - 1 ? '\u251C' : '\u2514'}\u2500 ${file.name} ${file.path} ${file.hash}`)
3725
})
38-
})
26+
}
3927

4028
const createFiles = (directory) => {
4129
return [{
@@ -52,25 +40,30 @@ const createFiles = (directory) => {
5240
}]
5341
}
5442

55-
const streamFiles = (directory, files, cb) => {
43+
const streamFiles = (ipfs, directory, files) => new Promise((resolve, reject) => {
5644
// Create a stream to write files to
5745
const stream = ipfs.addReadableStream()
58-
stream.on('data', function (data) {
46+
47+
stream.on('data', (data) => {
5948
log(`Added ${data.path} hash: ${data.hash}`)
6049

6150
// The last data event will contain the directory hash
6251
if (data.path === directory) {
63-
cb(null, data.hash)
52+
resolve(data.hash)
6453
}
6554
})
6655

56+
stream.on('error', reject)
57+
6758
// Add the files one by one
6859
files.forEach(file => stream.write(file))
6960

7061
// When we have no more files to add, close the stream
7162
stream.end()
72-
}
63+
})
7364

7465
const log = (line) => {
7566
document.getElementById('output').appendChild(document.createTextNode(`${line}\r\n`))
7667
}
68+
69+
main()

examples/browser-browserify/src/index.js

+11-18
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,30 @@
22

33
const IPFS = require('ipfs')
44

5-
const node = new IPFS({ repo: String(Math.random() + Date.now()) })
5+
document.addEventListener('DOMContentLoaded', async () => {
6+
const node = await IPFS.create({ repo: String(Math.random() + Date.now()) })
67

7-
node.once('ready', () => console.log('IPFS node is ready'))
8+
console.log('IPFS node is ready')
89

9-
function store () {
10-
const toStore = document.getElementById('source').value
10+
async function store () {
11+
const toStore = document.getElementById('source').value
1112

12-
node.add(Buffer.from(toStore), (err, res) => {
13-
if (err || !res) {
14-
return console.error('ipfs add error', err, res)
15-
}
13+
const res = await node.add(Buffer.from(toStore))
1614

1715
res.forEach((file) => {
1816
if (file && file.hash) {
1917
console.log('successfully stored', file.hash)
2018
display(file.hash)
2119
}
2220
})
23-
})
24-
}
25-
26-
function display (hash) {
27-
// buffer: true results in the returned result being a buffer rather than a stream
28-
node.cat(hash, (err, data) => {
29-
if (err) { return console.error('ipfs cat error', err) }
21+
}
3022

23+
async function display (hash) {
24+
// buffer: true results in the returned result being a buffer rather than a stream
25+
const data = await node.cat(hash)
3126
document.getElementById('hash').innerText = hash
3227
document.getElementById('content').innerText = data
33-
})
34-
}
28+
}
3529

36-
document.addEventListener('DOMContentLoaded', () => {
3730
document.getElementById('store').onclick = store
3831
})

examples/browser-create-react-app/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"dependencies": {
66
"dot-prop": "^5.0.0",
77
"ipfs": "file:../../",
8-
"ipfs-css": "^0.12.0",
8+
"ipfs-css": "^0.13.1",
99
"react": "^16.8.0",
1010
"react-dom": "^16.8.0",
1111
"react-scripts": "3.0.1",

examples/browser-create-react-app/src/hooks/use-ipfs-factory.js

+1-9
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ export default function useIpfsFactory ({ commands }) {
4040
} else {
4141
try {
4242
console.time('IPFS Started')
43-
ipfs = await promiseMeJsIpfs(Ipfs, {})
43+
ipfs = await Ipfs.create()
4444
console.timeEnd('IPFS Started')
4545
} catch (error) {
4646
console.error('IPFS init error:', error)
@@ -54,11 +54,3 @@ export default function useIpfsFactory ({ commands }) {
5454

5555
return { ipfs, isIpfsReady, ipfsInitError }
5656
}
57-
58-
function promiseMeJsIpfs (Ipfs, opts) {
59-
return new Promise((resolve, reject) => {
60-
const ipfs = new Ipfs(opts)
61-
ipfs.once('ready', () => resolve(ipfs))
62-
ipfs.once('error', err => reject(err))
63-
})
64-
}

examples/browser-mfs/index.js

+7-6
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,6 @@
33
/* eslint-env browser */
44

55
const IPFS = require('ipfs')
6-
const ipfs = new IPFS({
7-
repo: `ipfs-${Math.random()}`
8-
})
96
const {
107
dragDrop,
118
log,
@@ -25,11 +22,15 @@ const {
2522
} = require('./forms')
2623
const mime = require('mime-sniffer')
2724

28-
hideForms()
25+
document.addEventListener('DOMContentLoaded', async () => {
26+
const ipfs = await IPFS.create({
27+
repo: `ipfs-${Math.random()}`
28+
})
29+
30+
hideForms()
2931

30-
log('IPFS: Initialising')
32+
log('IPFS: Initialising')
3133

32-
ipfs.on('ready', () => {
3334
// Allow adding files to IPFS via drag and drop
3435
dragDrop(async (files) => {
3536
/* eslint-disable-next-line no-alert */

examples/browser-parceljs/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,6 @@
2626
"babel-plugin-transform-regenerator": "^6.26.0",
2727
"babel-polyfill": "^6.26.0",
2828
"parcel-bundler": "^1.10.3",
29-
"standard": "^12.0.1"
29+
"standard": "^13.1.0"
3030
}
3131
}

examples/browser-parceljs/public/index.js

+11-11
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
11
import 'babel-polyfill'
22
import IPFS from 'ipfs'
33

4-
// IPFS node setup
5-
const node = new IPFS({ repo: String(Math.random() + Date.now()) })
4+
document.addEventListener('DOMContentLoaded', async () => {
5+
// IPFS node setup
6+
const node = await IPFS.create({ repo: String(Math.random() + Date.now()) })
67

7-
// UI elements
8-
const status = document.getElementById('status')
9-
const output = document.getElementById('output')
8+
// UI elements
9+
const status = document.getElementById('status')
10+
const output = document.getElementById('output')
1011

11-
output.textContent = ''
12+
output.textContent = ''
1213

13-
function log (txt) {
14-
console.info(txt)
15-
output.textContent += `${txt.trim()}\n`
16-
}
14+
function log (txt) {
15+
console.info(txt)
16+
output.textContent += `${txt.trim()}\n`
17+
}
1718

18-
node.on('ready', async () => {
1919
status.innerText = 'Connected to IPFS :)'
2020

2121
const version = await node.version()

examples/browser-readablestream/index.js

+8-5
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,19 @@
33
/* eslint-env browser */
44

55
const Ipfs = require('../../')
6-
const videoStream = require('videostream')
7-
const ipfs = new Ipfs({ repo: 'ipfs-' + Math.random() })
6+
const VideoStream = require('videostream')
87
const {
98
dragDrop,
109
statusMessages,
1110
createVideoElement,
1211
log
1312
} = require('./utils')
1413

15-
log('IPFS: Initialising')
14+
document.addEventListener('DOMContentLoaded', async () => {
15+
const ipfs = await Ipfs.create({ repo: 'ipfs-' + Math.random() })
16+
17+
log('IPFS: Initialising')
1618

17-
ipfs.on('ready', () => {
1819
// Set up event listeners on the <video> element from index.html
1920
const videoElement = createVideoElement()
2021
const hashInput = document.getElementById('hash')
@@ -27,7 +28,7 @@ ipfs.on('ready', () => {
2728
log(`IPFS: Playing ${hashInput.value.trim()}`)
2829

2930
// Set up the video stream an attach it to our <video> element
30-
videoStream({
31+
const videoStream = new VideoStream({
3132
createReadStream: function createReadStream (opts) {
3233
const start = opts.start
3334

@@ -61,6 +62,8 @@ ipfs.on('ready', () => {
6162
return stream
6263
}
6364
}, videoElement)
65+
66+
videoElement.addEventListener('error', () => log(videoStream.detailedError))
6467
}
6568

6669
// Allow adding files to IPFS via drag and drop

examples/browser-readablestream/utils.js

+21-29
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
'use strict'
22

3-
const { Buffer } = require('../../')
4-
53
const log = (line) => {
4+
if (!line) return
5+
66
const output = document.getElementById('output')
77
let message
88

99
if (line.message) {
1010
message = `Error: ${line.message.toString()}`
11+
console.error(line)
1112
} else {
1213
message = line
1314
}
@@ -29,40 +30,31 @@ const dragDrop = (ipfs) => {
2930
event.preventDefault()
3031
}
3132

32-
container.ondrop = (event) => {
33+
container.ondrop = async (event) => {
3334
event.preventDefault()
3435

35-
Array.prototype.slice.call(event.dataTransfer.items)
36+
const files = Array.from(event.dataTransfer.items)
3637
.filter(item => item.kind === 'file')
3738
.map(item => item.getAsFile())
38-
.forEach(file => {
39-
const progress = log(`IPFS: Adding ${file.name} 0%`)
40-
41-
const reader = new window.FileReader()
42-
reader.onload = (event) => {
43-
ipfs.add({
44-
path: file.name,
45-
content: Buffer.from(event.target.result)
46-
}, {
47-
progress: (addedBytes) => {
48-
progress.textContent = `IPFS: Adding ${file.name} ${parseInt((addedBytes / file.size) * 100)}%\r\n`
49-
}
50-
}, (error, added) => {
51-
if (error) {
52-
return log(error)
53-
}
54-
55-
const hash = added[0].hash
56-
57-
log(`IPFS: Added ${hash}`)
58-
59-
document.querySelector('#hash').value = hash
60-
})
61-
}
6239

63-
reader.readAsArrayBuffer(file)
40+
for (const file of files) {
41+
const progress = log(`IPFS: Adding ${file.name} 0%`)
42+
const added = await ipfs.add({
43+
path: file.name,
44+
content: file
45+
}, {
46+
progress: (addedBytes) => {
47+
progress.textContent = `IPFS: Adding ${file.name} ${parseInt((addedBytes / file.size) * 100)}%\r\n`
48+
}
6449
})
6550

51+
const hash = added[0].hash
52+
53+
log(`IPFS: Added ${hash}`)
54+
55+
document.querySelector('#hash').value = hash
56+
}
57+
6658
if (event.dataTransfer.items && event.dataTransfer.items.clear) {
6759
event.dataTransfer.items.clear()
6860
}

examples/browser-script-tag/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
You can use IPFS in your in-browser JavaScript code with just a `<script>` tag.
44

5-
```
5+
```html
66
<script src="https://unpkg.com/ipfs/dist/index.min.js"></script>
77
```
88

0 commit comments

Comments
 (0)