Javascript 在继续使用Google Drive Api之前,如何等待file.get下载?
我正在尝试使用GoogleDrive API从GoogleDrive下载一个文件,似乎我在这里找到了一种实现方式。话虽如此,fs直到程序崩溃后才写入文件。这让我相信,我可以进行某种异步/等待文件实际下载,但我不太清楚具体在哪里 我试图使回调函数异步,并等待writeFile,但它似乎不起作用 imageHash.js 异步函数哈希器(){ ... ... ... for(让谷歌搜索谷歌帖子){ const googleDownload=sharedFunc.downloadGoogle(googlegimage.id);//应该在这里下载图像 const hash1=await imghash.hash('../images/options1.png',8,'binary');//我早些时候下载了这个图像,一切正常。 const hash2=await imghash.hash('../images/options2.jpg',8,'binary');//代码在此处生成错误 const comp=等待leven(hash1,hash2); 控制台日志(comp); ... ... } ... ... } moduleExports.jsJavascript 在继续使用Google Drive Api之前,如何等待file.get下载?,javascript,node.js,google-drive-api,fs,google-api-nodejs-client,Javascript,Node.js,Google Drive Api,Fs,Google Api Nodejs Client,我正在尝试使用GoogleDrive API从GoogleDrive下载一个文件,似乎我在这里找到了一种实现方式。话虽如此,fs直到程序崩溃后才写入文件。这让我相信,我可以进行某种异步/等待文件实际下载,但我不太清楚具体在哪里 我试图使回调函数异步,并等待writeFile,但它似乎不起作用 imageHash.js 异步函数哈希器(){ ... ... ... for(让谷歌搜索谷歌帖子){ const googleDownload=sharedFunc.downloadGoogle(goog
module.exports={
...
...
下载google:async(fileID)=>{
get({fileId:fileId,alt:'media'},{responseType:'arraybuffer'},
函数(err,{data}){
fs.writeFile(“../images/options2.jpg”,Buffer.from(数据),err=>{
if(err)console.log(err);
});
}
);
},
...
...
}
我还尝试使用带有谷歌驱动器链接的图像下载程序库,因为我可以轻松访问文件id,但它似乎无法下载图像,尽管有直接的url。如果有人知道如何使用这个库下载图像,我会接受这个答案,因为我已经知道如何等待库下载图像
如果您需要一个示例图像,您可以使用下面的一个
您可以将下载谷歌功能设置为承诺功能。更多细节可以在这里找到 基本上,你会
module.exports = {
...
...
downloadGoogle: (fileID) => {
return new Promise((resolve, reject) => { // make the function a promise
drive.files.get({fileId: fileID, alt: 'media'}, { responseType: "arraybuffer" },
function(err, { data }) {
fs.writeFile("../images/options2.jpg", Buffer.from(data), err => {
if (err) {
console.log(err);
return reject (err);
}
return resolve('file saved.')
});
}
);
});
},
...
...
}
然后你可以这样称呼它:
const googleDownload = await sharedFunc.downloadGoogle(googImage.id); //here is where it's supposed to download the image
如果你查看文档,谷歌会给出这个例子
var fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
var dest = fs.createWriteStream('/tmp/photo.jpg');
drive.files.get({
fileId: fileId,
alt: 'media'
})
.on('end', function () {
console.log('Done');
})
.on('error', function (err) {
console.log('Error during download', err);
})
.pipe(dest);