我发现了很多关于如何使用 API 从 google 驱动器检索
.txt
文件内容的帖子。我尝试过使用这个:
const drive = google.drive({version: 'v3', auth});
var data = drive.files.get({
fileId: file_id,
alt: "media"
});
data.execute(function(response){
console.log(reponse)
})
我的错误
data.execute(function(response){
^
TypeError: data.execute is not a function
还有
data.then
而不是 data.execute
每次出现错误时我都会研究并找不到解决方案。有人可以给我一个如何从文件 ID 获取文件内容的更新版本吗?因为我认为以前的答案有些过时了。
抱歉,如果这很明显。总的来说,我对 javascript 和 api 比较陌生。所以这对我有很大帮助,因为这是我完成程序之前的最后一段时间:)
谢谢,马蒂亚斯
当您为 Google Drive API 运行“drive.files.get”时,您会收到一个承诺,并获取您必须使用的数据。这是它的工作原理:
const filePath = `give_path_tosave_file`;
const dest = fs.createWriteStream(filePath);
let progress = 0;
drive.files.get(
{ fileId, alt: 'media' },
{ responseType: 'stream' }
).then(res => {
res.data
.on('end', () => {
console.log('Done downloading file.');
})
.on('error', err => {
console.error('Error downloading file.');
})
.on('data', d => {
d+='';
console.log(d);
//data will be here
// pipe it to write stream
}
})
.pipe(dest);
});
如果上述解决方案不起作用,您可以使用此解决方案。在谷歌官方网站上也可以做同样的事情:
var fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo';
var dest = fs.createWriteStream('/tmp/filename.txt');
drive.files.export({
fileId: fileId,
mimeType: 'application/txt'
})
.on('end', function () {
console.log('Done');
})
.on('error', function (err) {
console.log('Error during download', err);
})
.pipe(dest);
欲了解更多信息,您应该查看这里。
此外,以下方法将返回您有权访问驱动器中的所有文件。
drive.files.list({}, (err, res) => {
if (err) throw err;
const files = res.data.files;
if (files.length) {
files.map((file) => {
console.log(file);
});
} else {
console.log('No files found');
}
});
此处提供的解决方案不能正确处理并发。问题是这些函数将在文件的数据流结束之前结束。这是一个解决方案,函数将在文件数据流被消耗后结束:
import { google } from "googleapis"
const jwtClient = new google.auth.JWT("", undefined, "",
["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive"]
)
const googleDrive = google.drive("v3")
async function downloadFile(fileId: string): Promise<Buffer> {
await jwtClient.authorize()
const res = await googleDrive.files.get(
{ fileId, alt: "media", auth: jwtClient },
{ responseType: "stream" }
)
const buffers: any[] = []
await new Promise<void>((resolve, reject) => {
res.data
.on("end", () => {
console.log(`End of reading the file`)
resolve()
})
.on("error", err => {
reject(`Cannot create file ${err}`)
})
.on("data", chunk => {
buffers.push(chunk)
})
})
console.log(`End of the function`)
return Buffer.concat(buffers)
}
消息
End of reading the file
将先于消息 End of the function
打印。