forked from feross/chunk-store-stream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrite.js
50 lines (39 loc) · 1.39 KB
/
write.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
module.exports = ChunkStoreWriteStream
var BlockStream = require('block-stream2')
var inherits = require('inherits')
var stream = require('stream')
inherits(ChunkStoreWriteStream, stream.Writable)
function ChunkStoreWriteStream (store, chunkLength, opts) {
var self = this
if (!(self instanceof ChunkStoreWriteStream)) {
return new ChunkStoreWriteStream(store, chunkLength, opts)
}
stream.Writable.call(self, 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')
self._blockstream = new BlockStream(chunkLength, { zeroPadding: false })
self._blockstream
.on('data', onData)
.on('error', function (err) { self.destroy(err) })
var index = opts.startIndex || 0
function onData (chunk) {
if (self.destroyed) return
store.put(index, chunk)
self.emit('chunk', index)
index += 1
}
self.on('finish', function () { this._blockstream.end() })
}
ChunkStoreWriteStream.prototype._write = function (chunk, encoding, callback) {
this._blockstream.write(chunk, encoding, callback)
}
ChunkStoreWriteStream.prototype.destroy = function (err) {
if (this.destroyed) return
this.destroyed = true
if (err) this.emit('error', err)
this.emit('close')
}