1

I am really new to JavaScript and Node JS. I have various image URLs that I want to buffer. I have tried the request npm module but want a lower level library for what I want to achieve.

For example: http://assets.loeildelaphotographie.com/uploads/article_photo/image/128456/_Santu_Mofokeng_-_TOWNSHIPS_Shebeen_Soweto_1987.jpg

I see lots of examples that suggest using the request module or examples that save files to disk. However, I cannot find an HTTP GET request example that simply buffers the image so I can pass to another function. It needs to have an "end" event so I upload the buffered image data with confidence in another step. Is there a sample pattern or "how to" on this someone could provide? Thanks!

Community
  • 1
  • 1
mmryspace
  • 689
  • 1
  • 9
  • 18

1 Answers1

4

This is the native way:

var http=require('http'), imageBuffer;

http.get(
  'http://www.kame.net/img/kame-anime-small.gif',
  function(res) {
    var body=new Buffer(0);

    if (res.statusCode!==200) {
      return console.error('HTTP '+res.statusCode);
    }

    res.on('data', function(chunk) {
      body=Buffer.concat([body, chunk]);
    });

    res.on('end', function() {
      imageBuffer=body;
    });

    res.on('error', function(err) {
      console.error(err);
    });
  }
);

// Small webserver serving the image at http://127.0.0.1:4567
http.createServer(function(req, res) {
  res.write(imageBuffer || 'Please reload page');
  res.end();
}).listen(4567, '127.0.0.1');

and using request (encoding:null for binary response):

var request=require('request'), imageBuffer;

request({
  uri: 'http://www.kame.net/img/kame-anime-small.gif',
  encoding: null
}, function(err, res, body) {
  if (err) {
    return console.error(err);
  } else if (res.statusCode!==200) {
    return console.error('HTTP '+res.statusCode);
  }
  imageBuffer=body;
});

// Small webserver serving the image at http://127.0.0.1:4567
require('http').createServer(function(req, res) {
  res.write(imageBuffer || 'Please reload page');
  res.end();
}).listen(4567, '127.0.0.1');
Anatol - user3173842
  • 1,385
  • 1
  • 12
  • 16
  • 1
    does this also apply to a native HTTPS request? Could I get both `http` and `https` requests using the native `https` library? In other words can i pass `http` URLs into the `https`library? – mmryspace Apr 16 '16 at 21:39
  • @mmryspace pretty sure you will need to figure out what request type to use before sending off the request. – Liam Pillay Aug 13 '23 at 05:08