please bear in mind that I can, at best, be described as a rookie in both node and amazon S3. I have something app that writes to S3 in the background. I want to read from S3 when the file has been written, and only once it's been written. I attempt to check the number of objects and return the result:
function haveFilesBeenWrittenToBucket(bucketName, callback) {
s3.listObjects({ Bucket: bucketName }, function(err, data) {
const items = data.Contents;
callback(items);
});
}
and the readFile function:
OSClient.prototype.readFile = function(params, callback) {
haveFilesBeenWrittenToBucket(params.Bucket, items => {
console.log("Number of items " + items.length);
if (items.length > 0) {
const rl = readline.createInterface({
input: s3.getObject(params).createReadStream()
});
const myArray = [];
rl.on("line", function (line) {
const lineArray = line.split(",");
for (const value of lineArray) {
if (isNaN(value)) {
// line.split creates string elements, adding extraneous quotation marks in a string and converting
// number to string, so there is a need to reverse this process.
const slicedElement = value.slice(1, -1);
myArray.push(slicedElement);
} else {
const valueOfNumber = Number(value);
myArray.push(valueOfNumber);
}
}
})
.on("close", function () {
callback(myArray);
});
}
else{
var myfunction = this.readFile.bind(this, params, callback);
setTimeout(myfunction, 5000);
}
});
};
and lastly:
targetClient.readFile(params, function (arrayResult) {
logger.info("Read file:" + fileName + OS_FILE_SUFFIX);
readArray = arrayResult;
});
If I put a breakpoint on callback(items) (in 'haveFilesBeenWrittenToBucket') everything works fine and I get back the file written in the bucket, but if not, nothing seems to get written to S3. Seems like some race condition, but I'm really clueless and I really would appreciate some help. Is there a conflict between listing objects and writing to S3 (at least not until much later, in some other test, when it shouldn't be (it's part of a mocha test suite - the readFile is in async.waterfall). I have been on this for days and got nowhere. As I said, it's my first exposure to node, so please be patient with me. Thanks.