forked from storacha/ipfs-car
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfs.ts
87 lines (71 loc) · 1.86 KB
/
fs.ts
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import fs from 'fs'
import os from 'os'
import { CID } from 'multiformats'
import { BaseBlockstore } from 'blockstore-core'
import { Blockstore } from './index'
export class FsBlockStore extends BaseBlockstore implements Blockstore {
path: string
_opened: boolean
_opening?: Promise<void>
constructor () {
super()
this.path = `${os.tmpdir()}/${(parseInt(String(Math.random() * 1e9), 10)).toString() + Date.now()}`
this._opened = false
}
async _open () {
if (this._opening) {
await this._opening
} else {
this._opening = fs.promises.mkdir(this.path)
await this._opening
this._opened = true
}
}
async put (cid: CID, bytes: Uint8Array) {
if (!this._opened) {
await this._open()
}
const cidStr = cid.toString()
const location = `${this.path}/${cidStr}`
await fs.promises.writeFile(location, bytes)
}
async get (cid: CID): Promise<Uint8Array> {
if (!this._opened) {
await this._open()
}
const cidStr = cid.toString()
const location = `${this.path}/${cidStr}`
const bytes = await fs.promises.readFile(location)
return bytes
}
async has (cid: CID) {
if (!this._opened) {
await this._open()
}
const cidStr = cid.toString()
const location = `${this.path}/${cidStr}`
try {
await fs.promises.access(location)
return true
} catch (err) {
return false
}
}
async * blocks () {
if (!this._opened) {
await this._open()
}
const cids = await fs.promises.readdir(this.path)
for (const cidStr of cids) {
const location = `${this.path}/${cidStr}`
const bytes = await fs.promises.readFile(location)
yield { cid: CID.parse(cidStr), bytes }
}
}
async close () {
if (this._opened) {
await fs.promises.rm(this.path, { recursive: true })
}
this._opened = false
}
}