Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js knox s3 image retrieval

I'm trying to retrieve an image from s3 in node using the following:

app.get('/photos', function(req, res, next) {
var data = '';
s3.get('/tmp/DSC_0904.jpg').on('response', function(s3res){
    console.log(s3res.statusCode);
    console.log(s3res.headers);
    s3res.setEncoding('binary');
    s3res.on('data', function(chunk){
      data += chunk;
    });
    s3res.on('end', function() {
      res.contentType('image/jpeg');
      res.send(data);
    });
  }).end();
});

I'm open to suggestions as to why this doesn't work.

like image 613
jbg Avatar asked Oct 10 '22 03:10

jbg


2 Answers

I was able to download an image by making the following modifications in the end event callback:

s3res.on('end', function() {
    res.contentType('image/jpeg');
    res.write(data, encoding='binary')
    res.end()
});

I was having the same issues as the original poster. I suspected that since we set the encoding on the incoming buffer to binary we needed to do the same on the output stream. After some research I found the write method which excepts an encoding type as a parameter.

like image 66
Padraic Avatar answered Oct 18 '22 00:10

Padraic


You might like to use AwsSum since it is fully featured and maintained. It also has an examples/ directory which has a load of Amazon S3 examples in there:

  • https://github.com/appsattic/node-awssum/

There is also an example of exactly what you need in the node-awssum-scripts repository which is separate from the node-awssum one:

  • https://github.com/appsattic/node-awssum-scripts/blob/master/bin/amazon-s3-download.js

Let me know if you get on ok or if you need any help. Disclaimer: I'm the author of AwsSum. :)

like image 21
chilts Avatar answered Oct 17 '22 22:10

chilts