forked from ipfs/js-ipfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
76 lines (59 loc) · 1.73 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'use strict'
/* 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'
// 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: Buffer.from('one', 'utf8')
}, {
path: `${directory}/file2.txt`,
content: Buffer.from('two', 'utf8')
}, {
path: `${directory}/file3.txt`,
content: Buffer.from('three', 'utf8')
}]
}
const streamFiles = (directory, files, cb) => {
// Create a stream to write files to
const stream = ipfs.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`))
}