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!

1 Answer 1

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');
Sign up to request clarification or add additional context in comments.

2 Comments

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 httpslibrary?
@mmryspace pretty sure you will need to figure out what request type to use before sending off the request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.