All,
I have an array of sizes such as sizes = [20,40,60,80]
I need to loop over those, resize the src image to each size and name them appropriately.
Then, using knox, upload them to s3, and then remove the resized image.
Here is what I have:
http://jsfiddle.net/bpoppa/ZAcA7/
The problem is the flow control. When knox tries to putFile, I get an error saying it doesn't exist, which means knox is either running before the resize is done or it is already deleted at that point.
Any tips? All help is appreciated.
Thanks!
You need to remember that node.js code runs asynchronously. In your original code, the knox
code is running before image.resize
has completed (the callback is used to tell you when the operation has completed, not just to handle errors). Node won't wait for the callback and just continues to execute code in your function. You also need to be careful of using anonymous callbacks in for loops without creating a closure.
In general you want to use the callbacks to control program flow like the code below so that you only do the following action when the preceding action has completed.
var src = name + '.jpg';
for (var i = sizes.length - 1; i >= 0; i--) {
var k = i;
var dest = sizes[k] + '.jpg';
var s3 = sizes[k] + '.jpg';
resizeAndPut(src, dest, s3, sizes[k]);
}
fs.unlink(src); /* not sure what this is doing */
var resizeAndPut = function (src, dest, s3, size) {
easyimage.resize(
{
src: src,
dst: dest,
width: size,
height: size
}, function(err, image) {
if (err) throw err;
knox.putFile(dest, s3, function(err, res) { /* does image contain the path?, if so, might want to use image.path or the like instead of dest here */
if (err) throw err;
fs.unlink(dest); /* not sure what this is doing */
});
});
};