0

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
  • 609
  • 1
  • 8
  • 17

2 Answers2

3

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,305
  • 1
  • 13
  • 16
  • 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
0

Here's a simple example using the built-in streaming that the http response has:

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

var file = fs.createWriteStream("test.png");
var request = http.get("some URL to an image", function(response) {
  response.pipe(file);
});

I ran this myself and successfully downloaded an image from an external web site and saved it to a file and then loaded the file into the browser to see the same image.

jfriend00
  • 637,040
  • 88
  • 896
  • 906