Skip to content
This repository has been archived by the owner on Jan 12, 2024. It is now read-only.

Commit

Permalink
docs: update examples (#2319)
Browse files Browse the repository at this point in the history
Since I was going through these anyway to ensure they work with [0.37](ipfs/js-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/js-ipfs#1670 bubbles up to here.

License: MIT
Signed-off-by: Alan Shaw <alan.shaw@protocol.ai>
  • Loading branch information
Alan Shaw authored Aug 2, 2019
1 parent 3fce692 commit 32fd7ee
Show file tree
Hide file tree
Showing 34 changed files with 577 additions and 734 deletions.
49 changes: 21 additions & 28 deletions browser-add-readable-stream/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,27 @@
/* global Ipfs */
/* eslint-env browser */

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

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

// Our list of files
const files = createFiles(directory)

streamFiles(directory, files, (err, directoryHash) => {
if (err) {
return log(`There was an error adding the files ${err}`)
}
const directoryName = 'directory'

ipfs.ls(directoryHash, (err, files) => {
if (err) {
return log(`There was an error listing the files ${err}`)
}
// Our list of files
const inputFiles = createFiles(directoryName)

log(`
--
const directoryHash = await streamFiles(ipfs, directoryName, inputFiles)

Directory contents:
const fileList = await ipfs.ls(directoryHash)

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

files.forEach((file, index) => {
log(` ${index < files.length - 1 ? '\u251C' : '\u2514'}\u2500 ${file.name} ${file.path} ${file.hash}`)
})
})
fileList.forEach((file, index) => {
log(` ${index < fileList.length - 1 ? '\u251C' : '\u2514'}\u2500 ${file.name} ${file.path} ${file.hash}`)
})
})
}

const createFiles = (directory) => {
return [{
Expand All @@ -52,25 +40,30 @@ const createFiles = (directory) => {
}]
}

const streamFiles = (directory, files, cb) => {
const streamFiles = (ipfs, directory, files) => new Promise((resolve, reject) => {
// Create a stream to write files to
const stream = ipfs.addReadableStream()
stream.on('data', function (data) {

stream.on('data', (data) => {
log(`Added ${data.path} hash: ${data.hash}`)

// The last data event will contain the directory hash
if (data.path === directory) {
cb(null, data.hash)
resolve(data.hash)
}
})

stream.on('error', reject)

// Add the files one by one
files.forEach(file => stream.write(file))

// When we have no more files to add, close the stream
stream.end()
}
})

const log = (line) => {
document.getElementById('output').appendChild(document.createTextNode(`${line}\r\n`))
}

main()
29 changes: 11 additions & 18 deletions browser-browserify/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,30 @@

const IPFS = require('ipfs')

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

node.once('ready', () => console.log('IPFS node is ready'))
console.log('IPFS node is ready')

function store () {
const toStore = document.getElementById('source').value
async function store () {
const toStore = document.getElementById('source').value

node.add(Buffer.from(toStore), (err, res) => {
if (err || !res) {
return console.error('ipfs add error', err, res)
}
const res = await node.add(Buffer.from(toStore))

res.forEach((file) => {
if (file && file.hash) {
console.log('successfully stored', file.hash)
display(file.hash)
}
})
})
}

function display (hash) {
// buffer: true results in the returned result being a buffer rather than a stream
node.cat(hash, (err, data) => {
if (err) { return console.error('ipfs cat error', err) }
}

async function display (hash) {
// buffer: true results in the returned result being a buffer rather than a stream
const data = await node.cat(hash)
document.getElementById('hash').innerText = hash
document.getElementById('content').innerText = data
})
}
}

document.addEventListener('DOMContentLoaded', () => {
document.getElementById('store').onclick = store
})
2 changes: 1 addition & 1 deletion browser-create-react-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"dependencies": {
"dot-prop": "^5.0.0",
"ipfs": "file:../../",
"ipfs-css": "^0.12.0",
"ipfs-css": "^0.13.1",
"react": "^16.8.0",
"react-dom": "^16.8.0",
"react-scripts": "3.0.1",
Expand Down
10 changes: 1 addition & 9 deletions browser-create-react-app/src/hooks/use-ipfs-factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export default function useIpfsFactory ({ commands }) {
} else {
try {
console.time('IPFS Started')
ipfs = await promiseMeJsIpfs(Ipfs, {})
ipfs = await Ipfs.create()
console.timeEnd('IPFS Started')
} catch (error) {
console.error('IPFS init error:', error)
Expand All @@ -54,11 +54,3 @@ export default function useIpfsFactory ({ commands }) {

return { ipfs, isIpfsReady, ipfsInitError }
}

function promiseMeJsIpfs (Ipfs, opts) {
return new Promise((resolve, reject) => {
const ipfs = new Ipfs(opts)
ipfs.once('ready', () => resolve(ipfs))
ipfs.once('error', err => reject(err))
})
}
13 changes: 7 additions & 6 deletions browser-mfs/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
/* eslint-env browser */

const IPFS = require('ipfs')
const ipfs = new IPFS({
repo: `ipfs-${Math.random()}`
})
const {
dragDrop,
log,
Expand All @@ -25,11 +22,15 @@ const {
} = require('./forms')
const mime = require('mime-sniffer')

hideForms()
document.addEventListener('DOMContentLoaded', async () => {
const ipfs = await IPFS.create({
repo: `ipfs-${Math.random()}`
})

hideForms()

log('IPFS: Initialising')
log('IPFS: Initialising')

ipfs.on('ready', () => {
// Allow adding files to IPFS via drag and drop
dragDrop(async (files) => {
/* eslint-disable-next-line no-alert */
Expand Down
2 changes: 1 addition & 1 deletion browser-parceljs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,6 @@
"babel-plugin-transform-regenerator": "^6.26.0",
"babel-polyfill": "^6.26.0",
"parcel-bundler": "^1.10.3",
"standard": "^12.0.1"
"standard": "^13.1.0"
}
}
22 changes: 11 additions & 11 deletions browser-parceljs/public/index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import 'babel-polyfill'
import IPFS from 'ipfs'

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

// UI elements
const status = document.getElementById('status')
const output = document.getElementById('output')
// UI elements
const status = document.getElementById('status')
const output = document.getElementById('output')

output.textContent = ''
output.textContent = ''

function log (txt) {
console.info(txt)
output.textContent += `${txt.trim()}\n`
}
function log (txt) {
console.info(txt)
output.textContent += `${txt.trim()}\n`
}

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

const version = await node.version()
Expand Down
13 changes: 8 additions & 5 deletions browser-readablestream/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@
/* eslint-env browser */

const Ipfs = require('../../')
const videoStream = require('videostream')
const ipfs = new Ipfs({ repo: 'ipfs-' + Math.random() })
const VideoStream = require('videostream')
const {
dragDrop,
statusMessages,
createVideoElement,
log
} = require('./utils')

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

log('IPFS: Initialising')

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

// Set up the video stream an attach it to our <video> element
videoStream({
const videoStream = new VideoStream({
createReadStream: function createReadStream (opts) {
const start = opts.start

Expand Down Expand Up @@ -61,6 +62,8 @@ ipfs.on('ready', () => {
return stream
}
}, videoElement)

videoElement.addEventListener('error', () => log(videoStream.detailedError))
}

// Allow adding files to IPFS via drag and drop
Expand Down
50 changes: 21 additions & 29 deletions browser-readablestream/utils.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
'use strict'

const { Buffer } = require('../../')

const log = (line) => {
if (!line) return

const output = document.getElementById('output')
let message

if (line.message) {
message = `Error: ${line.message.toString()}`
console.error(line)
} else {
message = line
}
Expand All @@ -29,40 +30,31 @@ const dragDrop = (ipfs) => {
event.preventDefault()
}

container.ondrop = (event) => {
container.ondrop = async (event) => {
event.preventDefault()

Array.prototype.slice.call(event.dataTransfer.items)
const files = Array.from(event.dataTransfer.items)
.filter(item => item.kind === 'file')
.map(item => item.getAsFile())
.forEach(file => {
const progress = log(`IPFS: Adding ${file.name} 0%`)

const reader = new window.FileReader()
reader.onload = (event) => {
ipfs.add({
path: file.name,
content: Buffer.from(event.target.result)
}, {
progress: (addedBytes) => {
progress.textContent = `IPFS: Adding ${file.name} ${parseInt((addedBytes / file.size) * 100)}%\r\n`
}
}, (error, added) => {
if (error) {
return log(error)
}

const hash = added[0].hash

log(`IPFS: Added ${hash}`)

document.querySelector('#hash').value = hash
})
}

reader.readAsArrayBuffer(file)
for (const file of files) {
const progress = log(`IPFS: Adding ${file.name} 0%`)
const added = await ipfs.add({
path: file.name,
content: file
}, {
progress: (addedBytes) => {
progress.textContent = `IPFS: Adding ${file.name} ${parseInt((addedBytes / file.size) * 100)}%\r\n`
}
})

const hash = added[0].hash

log(`IPFS: Added ${hash}`)

document.querySelector('#hash').value = hash
}

if (event.dataTransfer.items && event.dataTransfer.items.clear) {
event.dataTransfer.items.clear()
}
Expand Down
2 changes: 1 addition & 1 deletion browser-script-tag/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

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

```
```html
<script src="https://unpkg.com/ipfs/dist/index.min.js"></script>
```

Expand Down
Loading

0 comments on commit 32fd7ee

Please sign in to comment.