0

I'm trying to use the node AWS SDK for uploading images but I have a problem when I'm using loop.

Here's my node module :

gm = require('gm').subClass imageMagick: true
s3 = require '../../modules/s3'
Photo = require '../../models/Photo'
sizes =
  t: 100
  m: 240
  z: 640
  l: 1024
  k: 2048
newPhoto = new Photo
newPhotoImg = gm process.cwd() + '/' + req.files.file.path
for key, val of sizes
  newPhotoImg
  .resize(null, val)
  .toBuffer 'jpg', (err, buffer) ->
    if err then console.error err and res.status(500).end() else
      params =
        Key: newPhoto.id + '-' + key + '.jpg'
        Body: buffer
        ContentType: 'image/jpeg'
      s3.putObject params, (err, data) ->
        if err then console.error err else console.log data

My s3 module works well and it is most probably not part of the problem.

The issue is I have a ETag returned for each size but when I look in my S3 Management Console, only the last item of loop (with the size 'k') is stored.

Can someone help me please ?

guduf
  • 412
  • 4
  • 14
  • Seems like you are doing the async looping in wrong way, use the `async` library for that. Similar problem described here http://stackoverflow.com/questions/21184340/async-for-loop-in-node-js – Risto Novik Jul 24 '15 at 11:57
  • @RistoNovik It works well with `async.forEachOf`. Thanks – guduf Jul 24 '15 at 12:07

1 Answers1

0

Like @RistoNovic said, I have to use async looping with the forEachOf function of async module.

uploadSize = (val, key, callback) ->
  newPhotoImg
  .resize null, val
  .toBuffer 'jpg', (err, buffer) ->
    if err then callback err else
      params =
        Key: newPhoto.id + '/' + newPhoto.id + '-' + key + '.jpg'
        Body: buffer
        ContentType: 'image/jpeg'
      s3.putObject params, (err, data) ->
        if err then callback err else callback()

async.forEachOf sizes, uploadSize, (err) ->
  if err then console.error err and res.status(500).send "Error with uploading image." else
    fs.unlinkSync process.cwd() + '/' + req.files.file.path
    newPhoto.save (err, doc) ->
      if err then console.error and res.status(500).send "Error with saving photo." else
        res.send doc
guduf
  • 412
  • 4
  • 14