Node.js(TypeScript)调用Google Drive API下载文件报错排查
Google Drive API下载文件时
pipe方法报错:Property 'pipe' does not exist on type 'GaxiosResponse<Schema$File>' 问题场景
尝试使用Google Drive API将HTML、CSS、JS等文件下载到本地存储时,遇到TypeScript类型错误。
原代码
const destinationFile = fs.createWriteStream(path.join(filePath, file.data.name || '')); const downloadStream = await drive.files.get({ fileId, alt: 'media' }); downloadStream.data.pipe(destinationFile) .on('finish', () => console.log("File downloaded:", file.data.name)) .on('error', (err: Error) => console.error("Error downloading file:", file.data.name, err));
错误信息
Property 'pipe' does not exist on type 'GaxiosResponse<Schema$File>'.ts(2339)
相关细节
- 生成的文件路径示例:
dist\output\xj1dh\src\setupTests.js downloadStream的结构:
{ config: { ... }, data: Blob { [Symbol(type)]: 'application/javascript', [Symbol(buffer)]: <Buffer 2f 2f 20 6a 65 73 74 2d 64 6f 6d 20 61 64 64 73 20 63 75 73 74 6f 6d 20 6a 65 73 74 20 6d 61 74 63 68 65 72 73 20 6f 72 20 61 73 73 65 72 74 69 6e ... 196 more bytes> }, headers: { ... }, status: 200, statusText: 'OK', request: { ... } }
错误原因
drive.files.get()默认返回GaxiosResponse对象,其中data字段为Buffer/Blob类型,并非Node.js可读流(Readable Stream),因此不支持pipe方法。
解决方案
方案1:获取可读流(推荐用于大文件)
在调用drive.files.get()时添加responseType: 'stream'配置,让返回的data变为可读流,即可正常使用pipe:
const destinationFile = fs.createWriteStream(path.join(filePath, file.data.name || '')); const downloadStream = await drive.files.get({ fileId, alt: 'media', responseType: 'stream' // 关键配置 }); downloadStream.data.pipe(destinationFile) .on('finish', () => console.log("File downloaded:", file.data.name)) .on('error', (err: Error) => console.error("Error downloading file:", file.data.name, err));
方案2:直接写入Buffer(适合小文件)
如果文件体积较小,也可以直接将Buffer写入本地文件,无需使用流:
import fs from 'fs/promises'; const downloadStream = await drive.files.get({ fileId, alt: 'media' }); const targetPath = path.join(filePath, file.data.name || ''); await fs.writeFile(targetPath, downloadStream.data); console.log("File downloaded:", file.data.name);
内容的提问来源于stack exchange,提问作者rutujp78
相关产品推荐
相关产品推荐

