Node.js调用Google Drive API下载文件报TypeError: Cannot read property 'on' of undefined
解决Google Drive API下载文件时的TypeError: Cannot read property 'on' of undefined问题
看起来你的问题出在代码里一个很容易忽略的变量覆盖问题上,我们来一步步拆解:
错误原因分析
你在downloadFiles函数里已经接收了fileId作为参数,但函数内部又重新声明了const fileId = '';——这会直接覆盖掉传入的有效文件ID,导致调用drive.files.get()时使用了空字符串作为文件ID。当Google Drive API收到无效的空ID请求时,返回的结果并不是预期的可监听事件的流对象,而是一个失败的响应(或者在某些版本的googleapis库中直接返回undefined),这就导致你调用.on()方法时抛出了Cannot read property 'on' of undefined的错误。
另外,你注释掉的const returnData = [];属于多余代码片段,和当前错误无关。
修正后的代码
把内部覆盖fileId的错误代码删掉,直接使用传入的参数即可:
const fs = require('fs'); const { google } = require('googleapis'); const Auth = require('../authorization/auth_drive/auth'); // get data var gotData = function downloadFiles(fileId, callback) { let content = fs.readFileSync('./GEARS/authorization/client_secret.json'); Auth(JSON.parse(content), (auth) => { const drive = google.drive({ version: 'v3', auth }); const dest = fs.createWriteStream('./test_files/test.png'); drive.files.get({fileId: fileId, alt: 'media'}) .on('end', () => { console.log('Done'); // 可在这里调用回调通知下载完成 callback(null, 'Download completed'); }) .on('error', err => { console.log('Error', err); // 错误时通过回调传递异常信息 callback(err); }) .pipe(dest); }); }; module.exports = gotData;
额外排查点
如果修正后仍然出现问题,可以检查以下几点:
- 确认传入的
fileId是有效的Google Drive文件ID,且该文件对当前授权账号有可读权限 - 检查你的
googleapis库版本是否和官方文档匹配,部分新版本库可能调整了流的返回方式(不过你其他功能正常,这个概率较低) - 确保
./test_files/目录存在,否则fs.createWriteStream会抛出文件系统错误
内容的提问来源于stack exchange,提问作者Richard Franek
相关产品推荐
相关产品推荐

