I have a sequence of events that go something like this:
//Download a file and write it to disk
await downloadSyncFile(user, downloadURL)
//Use the file...
await useTheFile() //Crash! The file is only partially there! Dangit!
My code keeps moving on before the file is actually on disk. Here's my download function:
async function downloadSyncFile(user, downloadURL){
//Setup download path
let path = './data/'+user+'/file.whatevs'
try{
//Download and save file
let stream = fs.createWriteStream(path)
let response = await axios.get(downloadURL, { responseType: 'stream' })
response.data.pipe(stream)
await new Promise(fulfill => stream.on('finish', fulfill))
}catch(error){
console.log('downloadSyncFile Error: '+error)
return { success: false, message: error }
}
}
Tthe downloadSyncFile()
function seems to be returning after the axios
download finishes, but the write to disk isn't done.
How can I make sure the file is safely written to disk before downloadSyncFile()
returns?