From e4d2a15143431a9af37a275a149621738c91aa00 Mon Sep 17 00:00:00 2001 From: achingbrain Date: Fri, 16 Feb 2018 18:08:05 +0000 Subject: [PATCH] docs: Add browser example for streaming files --- examples/README.md | 1 + .../browser-add-readable-stream/README.md | 7 ++ .../browser-add-readable-stream/index.html | 7 ++ examples/browser-add-readable-stream/index.js | 75 +++++++++++++++++++ 4 files changed, 90 insertions(+) create mode 100644 examples/browser-add-readable-stream/README.md create mode 100644 examples/browser-add-readable-stream/index.html create mode 100644 examples/browser-add-readable-stream/index.js diff --git a/examples/README.md b/examples/README.md index 4b6f82ddc1..f8e591eb4e 100644 --- a/examples/README.md +++ b/examples/README.md @@ -20,6 +20,7 @@ Let us know if you find any issue or if you want to contribute and add a new tut - [js-ipfs in the browser with WebPack](./browser-webpack) - [js-ipfs in the browser with a ` + + + diff --git a/examples/browser-add-readable-stream/index.js b/examples/browser-add-readable-stream/index.js new file mode 100644 index 0000000000..7ae4f87392 --- /dev/null +++ b/examples/browser-add-readable-stream/index.js @@ -0,0 +1,75 @@ +'use strict' + +/* global Ipfs */ +/* eslint-env browser */ + +const repoPath = 'ipfs-' + Math.random() +const ipfs = new Ipfs({ repo: repoPath }) + +ipfs.on('ready', () => { + const directory = 'directory' + + // 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}`) + } + + ipfs.ls(directoryHash, (err, files) => { + if (err) { + return log(`There was an error listing the files ${err}`) + } + + log(` +-- + +Directory contents: + +${directory}/ ${directoryHash}`) + + files.forEach((file, index) => { + log(` ${index < files.length - 1 ? '\u251C' : '\u2514'}\u2500 ${file.name} ${file.path} ${file.hash}`) + }) + }) + }) +}) + +const createFiles = (directory) => { + return [{ + path: `${directory}/file1.txt`, + + // content could be a stream, a url etc + content: ipfs.types.Buffer.from('one', 'utf8') + }, { + path: `${directory}/file2.txt`, + content: ipfs.types.Buffer.from('two', 'utf8') + }, { + path: `${directory}/file3.txt`, + content: ipfs.types.Buffer.from('three', 'utf8') + }] +} + +const streamFiles = (directory, files, cb) => { + // Create a stream to write files to + const stream = ipfs.files.addReadableStream() + stream.on('data', function (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) + } + }) + + // 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`)) +}