javascriptnode.jsamazon-s3downloadknox-amazon-s3-client

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.


Solution

  • 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.