var http require http var URL require url var request require request

 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
var http = require('http');
var URL = require('url');
var request = require('request');
http.createServer(onRequest).listen(3000);
function onRequest(req, res) {
var url = URL.parse(req.url, true).pathname.substring(1);
var bytesCopied = 0;
var contentLength = 0;
download(url, 0);
function download(url, firstByte) {
console.log('getting', url);
request({
url: url,
headers: {'Range': firstByte + '-'}
})
.on('response', function(response) {
contentLength = response.headers['content-length'];
if (firstByte == 0) {
res.writeHead(response.statusCode, response.headers);
}
})
.on('error', function(e) {
console.log('error, retrying starting with byte ' + bytesCopied);
download(url, bytesCopied);
})
.on('data', function(chunk) {
console.log('data chunk', chunk.length, 'bytes');
res.write(chunk);
bytesCopied += chunk.length;
})
.on('end', function() {
res.end();
});
}
}