Created
March 15, 2023 04:54
-
-
Save miguelmota/7815b5ea8f1d353e03b00fd4cf09922d to your computer and use it in GitHub Desktop.
JavaScript Pinata cloud IPFS upload example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from 'fs' | |
import path from 'path' | |
import pinataSDK from '@pinata/sdk' | |
require('dotenv').config() | |
const pinataApiKey = process.env.PINATA_API_KEY | |
const pinataSecretApiKey = process.env.PINATA_SECRET_API_KEY | |
export class IpfsUpload { | |
pinata = pinataSDK(pinataApiKey, pinataSecretApiKey) | |
constructor () { | |
this.pinata.testAuthentication().catch(err => { | |
console.error(err) | |
}) | |
} | |
async uploadJson (data: any) { | |
console.log('uploading json to ipfs') | |
const dirName = 'generated' | |
const dir = path.resolve(dirName) | |
if (!fs.existsSync(dir)) { | |
fs.mkdirSync(dir) | |
} | |
fs.writeFileSync(dir + '/data.json', JSON.stringify(data, null, 2)) | |
const res = await this.pinata.pinFromFS(dir, { | |
pinataOptions: { | |
wrapWithDirectory: false | |
} | |
}) | |
const ipfsHash = res.IpfsHash | |
console.log('uploaded to ipfs') | |
console.log(ipfsHash) | |
return ipfsHash | |
} | |
async uploadDir (dirPath: string) { | |
console.log('uploading dir to ipfs') | |
const res = await this.pinata.pinFromFS(dirPath, { | |
pinataOptions: { | |
wrapWithDirectory: false | |
} | |
}) | |
const ipfsHash = res.IpfsHash | |
console.log('uploaded to ipfs') | |
console.log(ipfsHash) | |
return ipfsHash | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment