-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathwrite.js
75 lines (59 loc) · 1.69 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* global File */
const { Writable } = require('readable-stream')
const toBuffer = require('typedarray-to-buffer')
class FileWriteStream extends Writable {
constructor (callback, opts) {
// inherit writable
super(Object.assign({ decodeStrings: false }, opts))
// when the stream finishes create a file
this.on('finish', this._generateFile.bind(this))
// create the internal buffers storage
this._buffers = []
this._bytesreceived = 0
this.callback = callback
this.type = (opts || {}).type
}
_createFile () {
// if we have no buffers, then abort any processing
if (this._buffers.length === 0) {
return
}
return new File(this._buffers, '', {
type: this.type || ''
})
}
_generateFile () {
const file = this._createFile()
if (file) {
if (typeof this.callback === 'function') {
this.callback(file)
}
this.emit('file', file)
}
// reset the buffers and counters
this._buffers = []
this._bytesreceived = 0
}
_preprocess (data, callback) {
// pass through the data
callback(null, data)
}
_write (chunk, encoding, callback) {
const data = Buffer.isBuffer(chunk) ? chunk : toBuffer(chunk)
const writeStream = this
this._preprocess(data, (err, processed) => {
if (err) {
return callback(err)
}
// if the incoming data has been passed through,
// then add to the bytes received buffer
if (processed) {
writeStream._bytesreceived += processed.length
writeStream._buffers.push(processed)
writeStream.emit('progress', writeStream._bytesreceived)
}
callback()
})
}
}
module.exports = FileWriteStream