This repository was archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathindex.js
67 lines (49 loc) · 1.59 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
'use strict'
/* global Ipfs */
/* eslint-env browser */
const main = async () => {
const repoPath = `ipfs-${Math.random()}`
const ipfs = await Ipfs.create({ repo: repoPath })
const directoryName = 'directory'
// Our list of files
const inputFiles = createFiles(directoryName)
const directoryHash = await streamFiles(ipfs, directoryName, inputFiles)
const fileList = await ipfs.ls(directoryHash)
log(`\n--\n\nDirectory contents:\n\n${directoryName}/ ${directoryHash}`)
fileList.forEach((file, index) => {
log(` ${index < fileList.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, a Buffer, a File etc
content: 'one'
}, {
path: `${directory}/file2.txt`,
content: 'two'
}, {
path: `${directory}/file3.txt`,
content: 'three'
}]
}
const streamFiles = (ipfs, directory, files) => new Promise((resolve, reject) => {
// Create a stream to write files to
const stream = ipfs.addReadableStream()
stream.on('data', (data) => {
log(`Added ${data.path} hash: ${data.hash}`)
// The last data event will contain the directory hash
if (data.path === directory) {
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()