【发布时间】:2021-03-09 01:21:43
【问题描述】:
我正在尝试使用 Google Drive API 从 Google Drive 下载一个文件,似乎我在post 中找到了一种实现方式。话虽如此, fs 直到程序崩溃后才会写入文件。这使我相信我可以执行某种异步/等待文件以实际下载,但我不太了解确切的位置。
我试图使回调函数异步并等待 writeFile 但它似乎不起作用。
imageHash.js
async function hasher() {
...
...
...
for (let googImage of googlePosts) {
const googleDownload = sharedFunc.downloadGoogle(googImage.id); //here is where it's supposed to download the image
const hash1 = await imghash.hash('../images/options1.png', 8, 'binary'); //I download this image earlier on and is fine.
const hash2 = await imghash.hash('../images/options2.jpg', 8, 'binary'); //code generates an error here
const comp = await leven(hash1, hash2);
console.log(comp);
...
...
}
...
...
}
moduleExports.js
module.exports = {
...
...
downloadGoogle: async (fileID) => {
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);
});
}
);
},
...
...
}
我还尝试使用带有 Google Drive 链接的图像下载器库,因为我可以轻松访问文件 ID,但尽管获得了直接 url,但它似乎无法下载图像。如果有人知道如何使用这个库下载图像,我会接受这个答案,因为我已经知道如何在库上等待下载图像。
如果您需要此示例图片,可以使用下面的图片
https://drive.google.com/uc?id=1ttF46_rexGt_ir2Wx-H9Oi58og4DGEYg
【问题讨论】:
标签: javascript node.js google-drive-api fs google-api-nodejs-client