Skip to content

Instantly share code, notes, and snippets.

@bellbind
Created May 30, 2023 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bellbind/bcb4596399ae1b16c0d4163dc82d8e99 to your computer and use it in GitHub Desktop.
Save bellbind/bcb4596399ae1b16c0d4163dc82d8e99 to your computer and use it in GitHub Desktop.
[nodejs][IPFS] helia basic example
// npm i helia @helia/unixfs
import * as helia from "helia";
import {unixfs} from "@helia/unixfs"; // unixfs support for large bytes
import {CID} from "multiformats/cid"; // helia.pins not support string CID
const node1 = await helia.createHelia(); // tcp network, stored on memory (not use files)
const node2 = await helia.createHelia();
const node1fs = unixfs(node1);
const node2fs = unixfs(node2);
await node1.libp2p.dial(node2.libp2p.getMultiaddrs()[0]); // connect directly
// example data
const blob = new Blob([new TextEncoder().encode("Hello World!")], {type: "text/plain;charset=utf-8"});
// publish blob as CID with addByteStream()
const cid = await node1fs.addByteStream(blob.stream());
console.log(cid);
const cidStr = cid.toString();
const cidAlt = CID.parse(cidStr);
const ret1 = await node1.pins.add(cidAlt); //NOTE: pins not accept CID string
console.log(ret1);
// NOTE: helia's pins needs stored blocks in blockstore (e.g. cannnot pin before stat()/ls()/cat())
const stat = await node2fs.stat(cidStr);
console.log(stat);
const ret2 = await node2.pins.add(cidAlt);
console.log(ret2);
// get CID object from CID string with ls() from @helia/unixfs
for await (const entry of node2fs.ls(cidStr)) console.log(entry.cid);
// retrieve data with cat(cid or cid-string)
const u8as = [];
for await (const u8a of node2fs.cat(cidStr)) u8as.push(u8a.slice());
console.log(await (new Blob(u8as).text()));
// stop only helia nodes; unixfs is just a wrapper
await Promise.all([node1.stop(), node2.stop()]);