I have to download multiple files from S3 bucket using node.js. For that I have to write a for loop
& call the s3.getObject(param)
method to download. After the files are downloaded I have to merge their contents.
I have written like this:
var fileContentList = new ArrayList();
for(i=0; i<fileNameList.length i++){
s3.getObject({ Bucket: "my-bucket", Key: fileNameList.get(i) }, function (error, data) {
if (error != null) {
alert("Failed to retrieve an object: " + error);
} else {
alert("Loaded " + data.ContentLength + " bytes");
fileContentList.add(data.Body.toString());
}
}
);
}
//Do merging with the fileContentList.
But as s3.getObject
is an asynchronous call the current thread moves on & nothing gets added to the fileContentList
while I am doing the merging.
How can I solve the problem? Any idea?
Is their any synchronous method in aws-sdk to download file?
Keep track of downloads you initiated in a separate list and as each download completes check to see if they are all done.
A more elegant solution, if you only want to merge the files if all downloads complete successfully:
You can use here async each, it will download all the files in parallel. In this example the download will continue if some of the files failed, if you want to stop downloading the files once an error occurred, call the callback with the error, this will call to the final callback immediately.
async documentation
I have solved using this. Though I have not tried the answers of Alexander,Lena & Sébastian I believe each of the answers mentioned by them would also work in this case. Many many thanks to them for their quick reply:
Promises is better way,