|
| 1 | +import fs from 'node:fs' |
| 2 | +import path from 'node:path' |
| 3 | +import { Blob } from 'node:buffer' |
| 4 | + |
| 5 | +async function* readAllFilesRecursively(root) { |
| 6 | + for (const entry of await fs.promises.readdir(root, { withFileTypes: true })) { |
| 7 | + const fullPath = path.join(root, entry.name) |
| 8 | + if (entry.isDirectory()) { |
| 9 | + yield* readAllFilesRecursively(fullPath) |
| 10 | + } else if (entry.isFile()) { |
| 11 | + yield fullPath |
| 12 | + } |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +const pinDirectoryToPinata = async (root) => { |
| 17 | + if (!root) throw new Error(`Usage: node pin-ens.mjs <directory>`) |
| 18 | + |
| 19 | + const formData = new FormData() |
| 20 | + |
| 21 | + for await (const file of readAllFilesRecursively(root)) { |
| 22 | + const relativePath = path.relative(root, file) || path.basename(file) |
| 23 | + const normalizedPath = relativePath.split(path.sep).join('/') |
| 24 | + const buffer = await fs.promises.readFile(file) |
| 25 | + formData.append('file', new Blob([buffer]), normalizedPath) |
| 26 | + console.info(`Added file: ${normalizedPath} (${file.length} bytes)`) |
| 27 | + } |
| 28 | + |
| 29 | + if (!process.env.PINATA_JWT) throw new Error(`PINATA_JWT environment variable is not set, cannot upload.`) |
| 30 | + |
| 31 | + const response = await fetch('https://api.pinata.cloud/pinning/pinFileToIPFS', { |
| 32 | + method: 'POST', |
| 33 | + headers: { Authorization: 'Bearer ' + process.env.PINATA_JWT }, |
| 34 | + body: formData, |
| 35 | + }) |
| 36 | + console.info(await response.text()) |
| 37 | +} |
| 38 | + |
| 39 | +pinDirectoryToPinata(process.argv[2]).catch((e) => { |
| 40 | + console.error(error) |
| 41 | + process.exitCode = 1 |
| 42 | +}) |
0 commit comments