SeanPlusPlus
SeanPlusPlus

Reputation: 9033

Check if ipfs data exists

Using the ipfs-http-client I can successfully add data using the below method. The console.log(added) returns an object with the path, cid, and size keys.

However, the console.log(exists) line returns Object [AsyncGenerator] {}.

I would like to be able to check if a data string exists. Is this possible?

import { create as ipfsHttpClient } from 'ipfs-http-client'

const ipfsClient = ipfsHttpClient('https://ipfs.infura.io:5001/api/v0')

const handleData = async (data) => {
  const added = await ipfsClient.add(data)
  console.log(added)

  const exists = await ipfsClient.get(data)
  console.log(exists)
}

handleData('hello world')

Upvotes: 2

Views: 844

Answers (1)

Pandemonium
Pandemonium

Reputation: 8390

The get method returns AsyncIterable<Uint8Array> object, which may be what you're printing out. To get each bytes, you will have to loop over it:

const cid = 'QmQ2r6iMNpky5f1m4cnm3Yqw8VSvjuKpTcK1X7dBR1LkJF'

for await (const buf of ipfs.get(cid)) {
  // do something with buf
  console.log(buf);
}

If all you care about is whether the data exists, you can just call next() method on the iterator and check for null or error.

const exists = (await ipfs.get(cid)).next() !== null

Upvotes: 1

Related Questions