UNPKG

1.13 kBJavaScriptView Raw
1const fs = require('fs')
2const path = require('path')
3const promisify = require('util').promisify
4const createHasher = require('multihasher')
5
6const isDirectory = dir => fs.statSync(dir).isDirectory()
7const writeFile = promisify(fs.writeFile)
8const readFile = promisify(fs.readFile)
9
10class FSAddressableStorage {
11 constructor (dir, hasher = createHasher('sha256')) {
12 /* This statement is tested but because it gets wrapped in a try/catch
13 the coverage report doesn't notice. */
14 /* istanbul ignore if */
15 if (!isDirectory(dir)) throw new Error('Not a directory.')
16 this.dir = dir
17 this._hasher = hasher
18 }
19 async set (value, ...args) {
20 if (!Buffer.isBuffer(value)) throw new Error('Invalid type.')
21 let hash = await this.hash(value, ...args)
22 await writeFile(path.join(this.dir, hash), value)
23 return hash
24 }
25 async hash (value, ...args) {
26 if (!Buffer.isBuffer(value)) throw new Error('Invalid type.')
27 return this._hasher(value, ...args)
28 }
29
30 async get (hash) {
31 return readFile(path.join(this.dir, hash))
32 }
33}
34
35module.exports = (...args) => new FSAddressableStorage(...args)