Created
July 5, 2014 11:06
-
-
Save tilap/e6842cf264123d2af5f3 to your computer and use it in GitHub Desktop.
nodejs: copy remote web file on local
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* copy remote web file on local | |
* | |
* usage: | |
* require('urlToFile')('http://domain.tld/image.jpg', '/local/path/image.jpg', function() {console.log('success !');}, function(message) {console.log(message);}); | |
*/ | |
var http = require('http'); | |
var fs = require('fs'); | |
module.exports = function(url, dest, successCallback, errorCallback) { | |
var file = fs.createWriteStream(dest); | |
var request = http.get(url, function(response) { | |
response.pipe(file); | |
file.on('finish', function() { | |
file.close(successCallback); | |
}); | |
}).on('error', function(err) { | |
fs.unlink(dest); | |
if (errorCallback) { | |
errorCallback(err.message); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment