-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
64 lines (53 loc) · 1.33 KB
/
index.js
File metadata and controls
64 lines (53 loc) · 1.33 KB
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
//source code copied from hughsk/nw-download
//https://github.com/hughsk/nw-download/blob/master/index.js
var through = require('through2')
var request = require('request')
var url = require('url')
var BufferHelper = require('bufferhelper')
module.exports = dwn
dwn._download = download // expose _download
function dwn(opts){
var uri = opts.uri
var progress = opts.progress || function(){}
var callback = opts.callback || function(){}
var callback_fired = false
var stream = download(uri)
var bufh = new BufferHelper()
stream.on('data', function(buf){
bufh.concat(buf)
})
stream.on('progress', progress)
stream.on('end', done)
stream.on('error', done)
function done(err){
if (callback_fired) {
return
}
callback_fired = true
if (err) {
callback(err)
return
}
callback(null, bufh.toBuffer())
}
}
function download(uri) {
var stream = through(write)
var progress = 0
var total = 0
request.head(uri, function(err, res) {
if (err) return stream.emit('error', err)
total = parseInt(res.headers['content-length'], 10)
request.get(uri).pipe(stream)
})
return stream
function write(data, _, next) {
this.push(data)
stream.emit('progress'
, (progress += data.length) / total
, progress
, total
)
next()
}
}