forked from svt/bridge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStaticFileRegistry.js
62 lines (54 loc) · 1.21 KB
/
StaticFileRegistry.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
53
54
55
56
57
58
59
60
61
62
// SPDX-FileCopyrightText: 2022 Sveriges Television AB
//
// SPDX-License-Identifier: MIT
const fs = require('fs')
const crypto = require('crypto')
class StaticFileRegistry {
/**
* Get the singleton
* instance of this class
* @returns { StaticFileRegistry }
*/
static getInstance () {
if (!this._instance) this._instance = new StaticFileRegistry()
return this._instance
}
constructor () {
/**
* @private
*/
this._map = new Map()
}
/**
* Get a read stream
* for a file with an id
* @param { String } id
* @returns { ReadableStream }
*/
createReadStream (id) {
const path = this._map.get(id)
if (!path) return
return fs.createReadStream(path)
}
/**
* Start serving the file at an absolute path
* @param { import('fs').PathLike } path
* @returns { String } An identifier for the file
*/
serve (path) {
const hash = crypto.createHash('sha256')
const id = hash.update(path).digest('hex')
this._map.set(id, path)
return id
}
/**
* Remove a file by its id
* from the registry
* @param { String } id
* @returns { Boolean }
*/
remove (id) {
this._map.delete(id)
}
}
module.exports = StaticFileRegistry