我有一系列的事件是这样的:
//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!
在文件实际在磁盘上之前,我的代码会继续运行。这是我的下载功能:
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 }
}
}
下载完成downloadSyncFile()
后,该功能似乎正在返回axios
,但未完成对磁盘的写入。
如何确保文件在downloadSyncFile()
返回之前安全地写入磁盘?