Upload files from a folder under a wrapping directory CID using ipfs-http-client and nodejs

Hello everyone,

You can use the ipfs-http-client Javascript library to add to IPFS multiple files from a folder, 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 ipfs-http-client.

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.

const {globSource, create} = require('ipfs-http-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()

After running the above piece of code with node, 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.

image

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:

1 Like