📗 示例 2: 201-Storage 存储配置详解
🎯 学习目标
理解 Helia 的存储架构,配置不同类型的持久化存储。
🏗️ 存储架构
Helia 使用两层存储系统:
┌─────────────────────────────────────────┐
│ Helia Node │
├──────────────────┬──────────────────────┤
│ Blockstore │ Datastore │
│ (数据块存储) │ (元数据存储) │
├──────────────────┼──────────────────────┤
│ 存储: CID -> 数据 │ 存储: 键 -> 值 │
│ 类型: Uint8Array │ 类型: Uint8Array │
└──────────────────┴──────────────────────┘
📦 Blockstore(块存储)
作用: 存储 IPFS 数据块(CID → Uint8Array)
内存存储(默认)
import { MemoryBlockstore } from 'blockstore-core'
const blockstore = new MemoryBlockstore()
const helia = await createHelia({ blockstore })
文件系统存储(Node.js)
import { FsBlockstore } from 'blockstore-fs'
const blockstore = new FsBlockstore('./ipfs-blocks')
const helia = await createHelia({ blockstore })
IndexedDB 存储(浏览器)
import { IDBBlockstore } from 'blockstore-idb'
const blockstore = new IDBBlockstore('ipfs-blocks')
await blockstore.open()
const helia = await createHelia({ blockstore })
S3 存储
import { S3Blockstore } from 'blockstore-s3'
const blockstore = new S3Blockstore({
bucket: 'my-ipfs-bucket',
// ... S3 配置
})
🗄️ Datastore(数据存储)
作用: 存储节点元数据、配置、DHT 数据等(字符串键 → Uint8Array 值)
内存存储
import { MemoryDatastore } from 'datastore-core'
const datastore = new MemoryDatastore()
const helia = await createHelia({ datastore })
LevelDB 存储(Node.js)
import { LevelDatastore } from 'datastore-level'
const datastore = new LevelDatastore('./ipfs-data')
const helia = await createHelia({ datastore })
IndexedDB 存储(浏览器)
import { IDBDatastore } from 'datastore-idb'
const datastore = new IDBDatastore('ipfs-data')
await datastore.open()
const helia = await createHelia({ datastore })
🔧 完整配置示例
import { createHelia } from 'helia'
import { FsBlockstore } from 'blockstore-fs'
import { LevelDatastore } from 'datastore-level'
// 持久化存储配置
const blockstore = new FsBlockstore('./ipfs-blocks')
const datastore = new LevelDatastore('./ipfs-data')
const helia = await createHelia({
blockstore,
datastore
})
console.log('Helia node with persistent storage started!')
console.log('Peer ID:', helia.libp2p.peerId.toString())
🧪 验证持久化
运行两次示例,你会发现:
- 第一次: 添加文件,生成 CID
- 第二次: 相同 CID 直接从本地 blockstore 获取,无需重新添加
// 检查本地是否存在
const hasBlock = await blockstore.has(cid)
console.log('Block exists locally:', hasBlock)
📊 存储实现对比
| 实现 | 环境 | 适用场景 |
|---|
MemoryBlockstore | 通用 | 测试、临时节点 |
FsBlockstore | Node.js | 服务器持久化 |
IDBBlockstore | 浏览器 | 客户端持久化 |
S3Blockstore | 通用 | 云存储、大规模部署 |
🚀 运行命令
npm run 201-storage
📌 下一步
学习网络配置,连接 P2P 网络 →
301-Networking