-
Notifications
You must be signed in to change notification settings - Fork 0
/
dat-storage.js
52 lines (46 loc) · 1.41 KB
/
dat-storage.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const path = require('path')
const fs = require('fs')
const detectSparseFiles = require('supports-sparse-files')
const raf = require('random-access-file')
const raif = require('random-access-indexed-file')
// globals
// =
const LARGE_FILES = ['data', 'signatures']
const INDEX_BLOCK_SIZE = {
data: 1024 * 1024, // 1mb
signatures: 1024 // 1kb
}
var supportsSparseFiles = false
// exported api
// =
exports.setup = async function () {
await new Promise((resolve) => {
detectSparseFiles(function (err, yes) {
supportsSparseFiles = yes
if (!yes) {
console.log('Sparse-file support not detected. Falling back to indexed data files.')
}
resolve()
})
})
}
function createStorage (folder, subfolder) {
return function (name) {
var filepath = path.join(folder, subfolder, name)
if (fs.existsSync(filepath + '.index')) {
// use random-access-indexed-file because that's what has been used
return raif(filepath, {blockSize: INDEX_BLOCK_SIZE[name]})
}
if (!supportsSparseFiles && LARGE_FILES.includes(name)) {
// use random-access-indexed-file because sparse-files are not supported and this file tends to get big
return raif(filepath, {blockSize: INDEX_BLOCK_SIZE[name]})
}
return raf(filepath)
}
}
exports.create = function (folder) {
return {
metadata: createStorage(folder, 'metadata'),
content: createStorage(folder, 'content')
}
}