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();
});
}
}