-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpublish-filecoin.js
82 lines (63 loc) · 2.28 KB
/
publish-filecoin.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
77
78
79
80
81
82
/*
This library is used to publish the compiled app to Filecoin.
The publishToFilecoin() function will upload the 'build' folder to Filecoin
via the web3.storage API.
The function will return an object that contains the CID of the uploaded
directory, and a URL for loading the app in a browser.
In order to run this script, you must obtain an API key from web3.storage.
That key should be saved to an environment variable named FILECOIN_TOKEN.
*/
const { Web3Storage, getFilesFromPath } = require('web3.storage')
const fs = require('fs')
async function publish () {
try {
const currentDir = `${__dirname}`
// console.log(`Current directory: ${dir}`)
const buildDir = `${currentDir}/../build`
// Get the Filecoin token from the environment variable.
const filecoinToken = process.env.FILECOIN_TOKEN
if (!filecoinToken) {
throw new Error(
'Filecoin token not detected. Get a token from https://web3.storage and save it to the FILECOIN_TOKEN environment variable.'
)
}
// Get a list of all the files to be uploaded.
const fileAry = await getFileList(buildDir)
// console.log(`fileAry: ${JSON.stringify(fileAry, null, 2)}`)
// Upload the files to Filecoin.
const cid = await uploadToFilecoin(fileAry, filecoinToken)
// console.log('Content added to Filecoin with CID:', cid)
// console.log(`https://${cid}.ipfs.dweb.link/`)
return cid
} catch (err) {
console.error(err)
}
}
function getFileList (buildDir) {
const fileAry = []
return new Promise((resolve, reject) => {
fs.readdir(buildDir, (err, files) => {
if (err) return reject(err)
files.forEach(file => {
// console.log(file)
fileAry.push(`${buildDir}/${file}`)
})
return resolve(fileAry)
})
})
}
async function uploadToFilecoin (fileAry, token) {
const storage = new Web3Storage({ token })
const files = []
for (let i = 0; i < fileAry.length; i++) {
const thisPath = fileAry[i]
// console.log('thisPath: ', thisPath)
const pathFiles = await getFilesFromPath(thisPath)
// console.log('pathFiles: ', pathFiles)
files.push(...pathFiles)
}
console.log(`Uploading ${files.length} files. Please wait...`)
const cid = await storage.put(files)
return cid
}
module.exports = publish