Script seems to be running before file is fully uploaded to GCS.
I have a blobStream.on function that is meant to only run when the data has finished uploading to GCS. The issue is it works sometimes and other time it is running too soon and forgets that another file is also uploading (normally it's the audio file that is still uploading).
I am wondering how can I improve the below script.
index
is the number of files uploading 0,1,2 it counts up.
fileLength
is the number of the file it is uploading 0,1,2 etc.
What seems to happy is that this part is triggering too soon, as the index and fileLength equal the same amount. It's not taking into account the data that could be because according to me doing a console.log(data)
nothing returns it's undefined
.
Seems a few errors here.
I am wondering is there anyway to watch the data
in this function and when that finished to run the correct script. Also clearly way too many delays - this is because I am trying to slow down the script so it runs at the correct time.
What I can say is that the delay
just after the blobStream.on('finish')
does seem to help it a little.
blobStream.on("finish", async (data) => {
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
await delay(10000);
const publicUrl = format(
`https://storage.googleapis.com/${bucket.name}/${blob.name}`
);
try {
await bucket.file(newfileName).makePublic();
} catch {
message.push({
message:
`Uploaded the file successfully: ${newfileName}, but public access is denied!`,
url: publicUrl,
});
}
console.log(index);
if(index == fileLength){
await delay(10000);
message.push({
originalname: file.originalname,
mimeType: file.mimetype,
message: "Uploaded the file successfully: " + newfileName,
url: publicUrl,
});
console.log(JSON.stringify(message))
await delay(10000)
console.log(JSON.stringify(message))
await delay(10000)
submitToDB(req, res, message);
//res.status(200).send(message);
}
else{
console.log("this is the first index."+ index +"file name "+ file.originalname);
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
message.push({
originalname: file.originalname,
mimeType: file.mimetype,
message: "Uploaded the file successfully: " + newfileName,
url: publicUrl,
})
await delay(1000)
console.log(JSON.stringify(message));
}
});