-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
227 lines (187 loc) · 5.38 KB
/
index.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
var os = require('os')
var fs = require('fs')
var path = require('path')
var async = require('async')
var crypto = require('crypto')
var fdSlicer = require('fd-slicer')
var assign = require('lodash.assign')
var DEFAULT_BLOCK_SIZE = 204800 // 200kb
/**
* Checks if `value` is classified as an `Array` object.
*
* @param value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @private
*/
function isArray (value) {
return Object.prototype.toString.call(value) === '[object Array]'
}
/**
* Sync function, Check if the file exists
*
* @param path The path to check.
* @returns {boolean} Returns `true` if `path` file exists, else `false`.
* @private
*/
function fsExistsSync (path) {
try {
return fs.statSync(path).isFile()
} catch (e) {
return false
}
}
var DEFAULT_OPTIONS = {
blockSize: DEFAULT_BLOCK_SIZE,
destPath: os.tmpdir(),
filename: Date.now() + ''
}
function FsSlice (filename, opts) {
if (!filename) {
throw new Error('require filename')
}
if (typeof filename !== 'string' && !Buffer.isBuffer(filename)) {
throw new Error('filename must be a string or Buffer')
}
if (!opts) opts = {}
this.OPTIONS = assign(DEFAULT_OPTIONS, opts)
if (typeof filename === 'string') {
try {
var stat = fs.statSync(filename)
if (!stat.isFile()) throw new Error(`no such file, stat '${filename}'`)
this.slicer = fdSlicer.createFromFd(fs.openSync(filename, 'r'))
this.filename = filename
this.filesize = stat.size
} catch (e) {
throw e
}
} else {
this.filename = this.OPTIONS.filename
this.filesize = filename.length
this.slicer = fdSlicer.createFromBuffer(filename)
}
}
/**
* Gets the block's size
* @param index of the block, `index` from 1 to a start
* @param blockSize Size of the block
* @returns {{start: number, end: number}}
* @private
*/
FsSlice.prototype._getBlockInterval = function (index, blockSize) {
index = index <= 0 ? 1 : index
blockSize = blockSize || this.OPTIONS.blockSize
var start = blockSize * (index - 1)
var end = blockSize * index
return {start, end}
}
/**
* The size of the block, calculate the number of blocks
* @returns {number}
*/
FsSlice.prototype._getBlockNum = function () {
return Math.ceil(this.filesize / this.OPTIONS.blockSize)
}
FsSlice.prototype.formatFilename = function (index) {
var filename = this.filename.split('/').pop()
index = index === undefined ? 1 : index
return crypto.randomBytes(16).toString('hex') + '_' + index + '_' + filename
}
FsSlice.prototype.slice = function (opts) {
if (!opts) opts = {}
opts = assign({
start: 0,
end: this._getBlockInterval(1).end
}, opts)
return this.slicer.createReadStream(opts)
}
FsSlice.prototype.sliceAsFile = function (filepath, rOptions, wOptions) {
if (!filepath) {
throw new Error('require filepath')
}
var self = this
if (typeof rOptions !== 'object') rOptions = {}
if (typeof wOptions !== 'object') wOptions = {}
return new Promise(function (resolve, reject) {
var writable = fs.createWriteStream(filepath, wOptions)
writable.on('finish', function () {
return resolve()
})
writable.on('error', function (err) {
return reject(err)
})
self.slice(rOptions).pipe(writable)
})
}
FsSlice.prototype.avgSliceAsFile = function (opts) {
opts = (typeof opts) === 'object' ? opts : {}
var self = this
var blockNum = this._getBlockNum()
var newFilePath = []
var index = opts.index || 1
return new Promise(function (resolve, reject) {
async.whilst(function () {
return index <= blockNum
}, function (callback) {
var newFilename = path.join(self.OPTIONS.destPath, self.formatFilename(index))
var blockInterval = self._getBlockInterval(index, self.OPTIONS.blockSize)
self
.sliceAsFile(newFilename, blockInterval)
.then(function () {
newFilePath.push(newFilename)
index++
return callback()
})
}, function (err) {
if (err) {
return reject(err)
}
return resolve(newFilePath)
})
})
}
FsSlice.prototype.join = function (filenameArray, writable) {
if (!isArray(filenameArray)) {
throw new Error('filenameArray must be an array')
}
if (!filenameArray.length) {
throw new Error('filenameArray is empty')
}
for (var i in filenameArray) {
if (!fsExistsSync(filenameArray[i])) {
throw new Error(filenameArray[i] + ' file does not exist')
}
}
return new Promise(function (resolve, reject) {
writable.on('finish', function () {
return resolve()
})
writable.on('error', function (err) {
return reject(err)
})
async.eachSeries(filenameArray, function (file, callback) {
var filenameFd = fs.openSync(file, 'r')
var slicer = fdSlicer.createFromFd(filenameFd)
var readable = slicer.createReadStream()
readable.on('end', function () {
fs.closeSync(filenameFd)
return callback()
})
readable.pipe(writable, {end: false})
}, function (err) {
if (err) {
return reject(err)
}
writable.end()
writable.destroy()
})
})
}
FsSlice.prototype.joinAsFile = function (filenameArray, filepath) {
return this.join(filenameArray, fs.createWriteStream(filepath))
}
/**
* Expose `FsSlice`
*/
module.exports = function (filename, opts) {
return new FsSlice(filename, opts)
}