forked from feross/chunk-store-stream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread.js
48 lines (39 loc) · 1.32 KB
/
read.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
module.exports = ChunkStoreReadStream
var inherits = require('inherits')
var stream = require('stream')
inherits(ChunkStoreReadStream, stream.Readable)
function ChunkStoreReadStream (store, chunkLength, opts) {
if (!(this instanceof ChunkStoreReadStream)) {
return new ChunkStoreReadStream(store, chunkLength, opts)
}
stream.Readable.call(this, opts)
if (!opts) opts = {}
if (!store || !store.put || !store.get) {
throw new Error('First argument must be an abstract-chunk-store compliant store')
}
chunkLength = Number(chunkLength)
if (!chunkLength) throw new Error('Second argument must be a chunk length')
this._length = opts.length || store.length
if (!Number.isFinite(this._length)) throw new Error('missing required `length` property')
this._store = store
this._chunkLength = chunkLength
this._index = opts.startIndex || 0
}
ChunkStoreReadStream.prototype._read = function () {
var self = this
if (self._index * self._chunkLength >= self._length) {
self.push(null)
} else {
self._store.get(self._index, function (err, chunk) {
if (err) return self.destroy(err)
self.push(chunk)
})
}
self._index += 1
}
ChunkStoreReadStream.prototype.destroy = function (err) {
if (this.destroyed) return
this.destroyed = true
if (err) this.emit('error', err)
this.emit('close')
}