Skip to content

Instantly share code, notes, and snippets.

@niklasfi
Created January 28, 2011 07:48
Show Gist options
  • Save niklasfi/799968 to your computer and use it in GitHub Desktop.
Save niklasfi/799968 to your computer and use it in GitHub Desktop.
var fs = require('fs');
var http = require('http');
var urlparser = require('url');
var k = process.binding('constants');
function Download(url,path){
this.u= urlparser.parse(url);
this.httpStatus=null;
this.recievedHeader=null;
this.filestats = {filesize: null, bytesWritten: 0, bytesRecieved: 0}
this.timer = {timerObject: null, timerInterval: 2000}
this.fd = null;
this.Download(url,path);
}
Download.prototype = {
Download: function (url,path){
fs.open(path, k.O_WRONLY | k.O_CREAT, 0666, function(err, fd){
if(err){
console.error("Got error while opening file: " + err.message);
process.exit(1);
}
this.fd=fd;
this.startDownload();
});
},
startDownload: function(){
var options={host: this.u.host, port: this.u.port ||'80', path: this.u.pathname, method: 'GET'};
var g=http.get(options);
g.on('response', function(res) {
console.log('got response: ' + res.statusCode);
this.recievedHeader=res.headers;
this.httpStatus=res.statusCode;
res.on('data',onNewData);
});
g.on('error', function(e) {
console.log('got error while sending get request: ' + e.message);
process.exit(2);
});
g.on('end', function() {
console.log('download complete');
});
},
onNewData: function(chunk){
this.filestats.bytesRecieved += chunk.length;
fs.write(fd, chunk, 0, chunk.length, null, function(err, written){
this.filestats.bytesWritten += written;
if( (this.filestats.filesize == this.filestats.bytesWritten || this.terminate)
&& this.filestats.bytesWritten == this.filestats.bytesRecieved){
fs.close(fd);
console.log('all bytes written');
}
});
}
}
var d = new Download('http://dl.google.com/earth/client/current/GoogleEarthLinux.bin', 'googleearth.bin');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment