Google Drive API的drive.files.list无文件返回,如何遍历子文件夹?
Google Drive API 无文件返回排查与子文件夹遍历方案
一、无文件返回的常见排查点
- 权限验证:确认目标文件夹已共享给你的服务账号邮箱(service_email),共享权限至少为「查看者」。服务账号无法访问未授权的私有文件夹。
- 查询条件优化:原查询仅筛选父文件夹,建议添加排除回收站文件的条件,确保只返回有效内容:
q: `'${folderId}' in parents and trashed = false` - 字段补充:需获取
mimeType来区分文件和文件夹,修改fields参数以获取必要信息:fields: 'nextPageToken, files(id, name, mimeType)' - 分页处理:原代码pageSize设为10,若文件夹内内容超过10条,需通过
nextPageToken循环获取全部内容,避免遗漏。
二、递归遍历子文件夹的实现代码
以下是修改后的完整代码,包含递归遍历所有子文件夹及文件的逻辑:
const { JWT } = require('google-auth-library') const { google } = require('googleapis') // 获取认证实例 const getAuth = ({ email, key }) => { const scopes = ['https://www.googleapis.com/auth/drive'] return new JWT({ email, key, scopes, }) } // 递归遍历文件夹及其子内容 async function traverseFolder(drive, folderId, depth = 0) { const indent = ' '.repeat(depth) try { // 分页获取当前文件夹下所有非回收站的文件和文件夹 let nextPageToken = null do { const res = await drive.files.list({ pageToken: nextPageToken, fields: 'nextPageToken, files(id, name, mimeType)', q: `'${folderId}' in parents and trashed = false`, spaces: 'drive', }) const items = res.data.files || [] for (const item of items) { const type = item.mimeType === 'application/vnd.google-apps.folder' ? '[文件夹]' : '[文件]' console.log(`${indent}${type} ${item.name} (${item.id})`) // 如果是文件夹,递归遍历子内容 if (item.mimeType === 'application/vnd.google-apps.folder') { await traverseFolder(drive, item.id, depth + 1) } } nextPageToken = res.data.nextPageToken } while (nextPageToken) } catch (e) { console.error(`${indent}遍历失败: ${e.message}`) } } async function loadDrive(options) { const { folderId, key, service_email } = options const auth = await getAuth({ email: service_email, key }) const drive = google.drive({ version: 'v3', auth }) console.log(`开始遍历根文件夹: ${folderId}`) await traverseFolder(drive, folderId) }
代码说明
traverseFolder函数通过递归处理子文件夹,用depth参数控制缩进,输出层级清晰易读。- 实现分页逻辑,确保获取文件夹下所有内容,不受pageSize限制。
- 通过
mimeType区分文件与文件夹,仅对文件夹执行递归遍历。 - 添加错误捕获,单个文件夹遍历失败不会中断整个遍历流程。
内容的提问来源于stack exchange,提问作者Cameron
相关产品推荐
相关产品推荐

