playing around with node js and an image downloader. I stumbled on a problem with urls and http.get
, which failed for me if the url contained spaces in the query. I managed to get around the problem by escaping just the url path myself. if I use url.parse()
the path variable will be cut off at the first space. My solution works but I wondered if there is a better solution.
function downloadFileFromURL( file_url, callback )
{
//-------------
// really complicated way to get a http.get save path
var protocol = url.parse( file_url).protocol;
var host = url.parse( file_url ).host;
var full_domain = protocol + '//' + host;
var escaped_path = escape(file_url.substring( full_domain.length ));
var options = {
host: host
, port: 80
, path: escaped_path
}
var file_url_info = url.parse( file_url );
var file_path = path.join( __dirname, 'images', path.basename(file_url) );
var request = http.get( options , function(res){
var imagedata = ''
res.setEncoding('binary')
res.on('data', function(chunk){
imagedata += chunk;
})
res.on('end', function(){
fs.writeFile( file_path, imagedata, 'binary', function(err){
if (err) callback( err );
else {
callback( null, file_path );
}
})
})
})
}
Try running it through encodeURI
.
var encoded_url = encodeURI(file_url);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With