-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstorage.ts
38 lines (35 loc) · 942 Bytes
/
storage.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
import os from 'os'
import fs from 'fs'
import path from 'path'
import type { AnyIterable } from './index.js'
const createTempDir = () => {
const base = `${path.join(os.tmpdir(), 'external-merge-sort')}${path.sep}`
if (!fs.existsSync(base)) {
fs.mkdirSync(base)
}
return fs.mkdtempSync(base)
}
export type Write<T> = (chunk: AnyIterable<T>, filename: string) => Promise<AnyIterable<T>>
export const createStore = <T>(write: Write<T>, extension = '') => {
let temp: string | undefined
let i = 0
return {
write: (chunk: AnyIterable<T>) => {
if (!temp) {
temp = createTempDir()
}
const filename = path.join(temp, `temp${++i}${extension}`)
return write(chunk, filename)
},
dispose: async () => {
if (temp) {
try {
fs.rmSync(temp, { recursive: true, force: true })
}
catch {
// softfail if rmdir fails
}
}
}
}
}