Hello everyone,
You can use the kubo-rpc-client
Javascript library to add multiple files from a folder to IPFS, under a CID that wraps them all together, by making use of the globSource
utility. In order to do so, please follow the below steps:
Install the library from the official kubo-rpc-client repository. Note that if you’ve previously used the ipfs-http-client
to upload content to IPFS, it was deprecated and we recommend using the kubo
client going forward.
Define your Infura client together with an auth header, then create an options
variable having the value wrapWithDirectory
equal to true
and use it as an optional parameter with the globSource
utility.
Add the content to your Infura IPFS project by specifying the path
to your directory from where the files will be fetched together with a pattern
(**/*) to match the files under your path.
Don’t forget to use your Project ID and API Key Secret.
Also keep in mind that the
kubo
client can only be imported as a module, so for simplicity save the below piece of code as an mjs
file, index.mjs for example, before running it in node
.
Still if you wish to use .js
files instead .mjs
you will need to add the top-level field "type"
with a value of "module"
in the nearest package.json
file as explained here.
You can also create an empty package.json
file in your project directory and add the below to get it working as a .js
file.
// package.json
{
"type": "module"
}
So here’s the code:
import { create, globSource } from 'kubo-rpc-client'
const projectId = '27hxxxxRsj';
const projectSecret = '205xxxx15b';
async function wrapWithDir(){
const auth =
'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64')
const client = await create({
host: 'ipfs.infura.io',
port: 5001,
protocol: 'https',
headers: {
authorization: auth
}
})
const options = {
wrapWithDirectory: true
}
for await (const file of client.addAll(globSource("/home/user/path/to/directory", "**/*" ), options)) {
console.log(file)
}
}
wrapWithDir()
The output of the code run will display the CIDs of each individual file contained in your folder together with the CID which wraps them all together, as highlighted with orange in the example below.
You can use to the wrapping CID to access the content via your Infura Dedicated Gateway or you can view the files in the IPFS explorer from your Infura account:
Clicking the wrapping CID will reveal the uploaded files: