Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http.get with urls with spaces

Tags:

node.js

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

    })
}
like image 364
Thomas Traum Avatar asked Jul 22 '12 23:07

Thomas Traum


1 Answers

Try running it through encodeURI.

var encoded_url = encodeURI(file_url);
like image 84
Waylon Flinn Avatar answered Nov 02 '22 22:11

Waylon Flinn