我和我的团队尝试了多种方法来解决这个问题,但是每当我们去下载文件时,我们都会收到错误消息,指出该文件不存在。
执行此操作的典型方法是什么?这看起来应该很容易,但我似乎找不到任何有效的方法。
澄清一下,我的 Node JS 运行一个将文件上传到一个存储桶的函数。这会触发一个云函数,该函数会进行一些处理,然后将文件上传到另一个存储桶。我希望 Node JS 等待其他文件上传,然后下载该文件。
const storage = new Storage();
const bucket = storage.bucket('receipttext');
async function uploadFile() {
await storage.bucket("BUCKET_ONE").upload('FILE_PATH', {
gzip: true,
metadata: {
cacheControl: 'public, max-age=31536000',
},
});
console.log('step1!');
const options = {
destination: 'DOWNLOAD_PATH',
};
//Something needs to go here to cause Node JS to wait until the file exists
let file = null;
let ifExist = false;
while(!ifExist) {
console.log('step1.1!');
file = await storage
.bucket("BUCKET_TWO")
.file('FILE_NAME');
ifExist = file.exists();
//console.log('step1.2!',ifExist);
console.log('step2!');
}
//Downloads the File
await file.download(options).catch(function(error){
console.log(2);
});
console.log(
`gs:// downloaded .`
);
console.log('step3!');
let obj = JSON.parse(fs.readFileSync('DOWNLOAD_PATH', 'utf8'));
console.log(obj,"here");
res.json({response: obj});
}
uploadFile().catch(console.error);
console.log("successUpload");
您唯一缺少的是await关键字,因为exists()方法返回一个承诺(始终为布尔值true),它解析为数组的第一个元素是您需要的布尔值。
所以我会像这样调整线路:
ifExist = (await file.exists())[0]; // (await brackets) needed