Node.js
Setup a Node.js Project
To start you can go to your terminal and put in the following code
mkdir pinata-starter && cd pinata-starter && npm init -y
Then install the Pinata SDK as well as dotenv
npm i pinata dotenv
In the root of the directory make a .env
file where we’re pull the following variables.
PINATA_JWT=
GATEWAY_URL=
Use the JWT
from the API key creation in the previous step as well as the Gateway Domain
. The format of the Gateway domain should be mydomain.mypinata.cloud
.
Now we’ll make two files, index.js
and hello-world.txt
.
touch index.js && touch hello-world.txt
Inside the hello-world.txt
you can put whatever you’d like such as Hello from IPFS!
.
Upload a File to Pinata
Once we have our initial project setup we can put the following code into our index.js
file.
You can run this by using node index.js
in the terminal. After uploading a file you should get a response that looks like this
{
id: "349f1bb2-5d59-4cab-9966-e94c028a05b7",
name: "file.txt",
cid: "bafybeihgxdzljxb26q6nf3r3eifqeedsvt2eubqtskghpme66cgjyw4fra",
size: 4682779,
number_of_files: 1,
mime_type: "text/plain",
user_id: "7a484d2c-4219-4f80-9d9d-86b42461e71a",
group_id: null
}
Fetch the File through a Gateway
With the cid
you can view the file or fetch the data using your Gateway. Lets make a new file called fetch.js
and put in the following code.
const { PinataSDK } = require("pinata")
require("dotenv").config()
const pinata = new PinataSDK({
pinataJwt: process.env.PINATA_JWT,
pinataGateway: process.env.GATEWAY_URL
})
async function main() {
try {
const file = await pinata.gateways.get("bafkreiac3t35fklpiwqonav2vj4x2dh6x2zugkdu7dsh6zkaq5jr33lcwy")
console.log(file.data)
} catch (error) {
console.log(error);
}
}
main()