-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathexample.js
31 lines (23 loc) · 886 Bytes
/
example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* eslint-disable no-console */
import * as dagPB from '@ipld/dag-pb'
import { CID } from 'multiformats/cid'
import { sha256 } from 'multiformats/hashes/sha2'
async function run () {
const bytes = dagPB.encode({
Data: new TextEncoder().encode('Some data as a string'),
Links: []
})
// also possible if you `import dagPB, { prepare } from '@ipld/dag-pb'`
// const bytes = dagPB.encode(prepare('Some data as a string'))
// const bytes = dagPB.encode(prepare(new TextEncoder().encode('Some data as a string')))
const hash = await sha256.digest(bytes)
const cid = CID.create(1, dagPB.code, hash)
console.log(cid, '=>', Buffer.from(bytes).toString('hex'))
const decoded = dagPB.decode(bytes)
console.log(decoded)
console.log(`decoded "Data": ${new TextDecoder().decode(decoded.Data)}`)
}
run().catch((err) => {
console.error(err)
process.exit(1)
})