Escribir la imagen en el servidor local


Update

La respuesta aceptada fue buena para el año pasado, pero hoy usaría el paquete que todos los demás usan: https://github.com/mikeal/request


Original

Estoy tratando de agarrar el logotipo de Google y guardarlo en mi servidor con nodo.js.

Esto es lo que tengo ahora mismo y no funciona:

        var options = {
            host: 'google.com',
            port: 80,
            path: '/images/logos/ps_logo2.png'
        };

        var request = http.get(options);

        request.on('response', function (res) {
            res.on('data', function (chunk) {
                fs.writeFile(dir+'image.png', chunk, function (err) {
                    if (err) throw err;
                    console.log('It\'s saved!');
                });
            });
        });

¿Cómo puedo hacer que esto funcione?

Author: serv-inc, 2011-03-14

4 answers

Algunas cosas están sucediendo aquí:

  1. Asumo que requirió fs / http, y estableció la variable dir:)
  2. google.com redirige a www.google.com, por lo que está guardando el cuerpo de la respuesta de redirección, no la imagen
  3. la respuesta se transmite en streaming. eso significa que el evento "datos" se dispara muchas veces, no una vez. usted tiene que guardar y unir todos los trozos juntos para obtener el cuerpo de respuesta completa
  4. dado que está obteniendo datos binarios, debe configurar la codificación en consecuencia en la respuesta y WriteFile (el valor predeterminado es utf8)

Esto debería funcionar:

var http = require('http')
  , fs = require('fs')
  , options

options = {
    host: 'www.google.com'
  , port: 80
  , path: '/images/logos/ps_logo2.png'
}

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('logo.png', imagedata, 'binary', function(err){
            if (err) throw err
            console.log('File saved.')
        })
    })

})
 77
Author: Ricardo Tomasi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-07 22:43:26

Este hilo es viejo, pero quería hacer las mismas cosas con el https://github.com/mikeal/request paquete.

Aquí un ejemplo de trabajo

var fs      = require('fs');
var request = require('request');
// Or with cookies
// var request = require('request').defaults({jar: true});

request.get({url: 'https://someurl/somefile.torrent', encoding: 'binary'}, function (err, response, body) {
  fs.writeFile("/tmp/test.torrent", body, 'binary', function(err) {
    if(err)
      console.log(err);
    else
      console.log("The file was saved!");
  }); 
});
 33
Author: m4tm4t,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-10 09:30:58

Le sugiero que use http-request, para que incluso se gestionen las redirecciones.

var http = require('http-request');
var options = {url: 'http://localhost/foo.pdf'};
http.get(options, '/path/to/foo.pdf', function (error, result) {
    if (error) {
        console.error(error);
    } else {
        console.log('File downloaded at: ' + result.file);
    }
});
 26
Author: Drasill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-26 13:06:05

¿Qué tal esto?

var http = require('http'), 
fs = require('fs'), 
options;

options = {
    host: 'www.google.com' , 
    port: 80,
    path: '/images/logos/ps_logo2.png'
}

var request = http.get(options, function(res){

//var imagedata = ''
//res.setEncoding('binary')

var chunks = [];

res.on('data', function(chunk){

    //imagedata += chunk
    chunks.push(chunk)

})

res.on('end', function(){

    //fs.writeFile('logo.png', imagedata, 'binary', function(err){

    var buffer = Buffer.concat(chunks)
    fs.writeFile('logo.png', buffer, function(err){
        if (err) throw err
        console.log('File saved.')
    })

})
 5
Author: yuqin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-05 03:07:39