You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Puppeteer下载的文件直接传入Google AppScript或对接Drive API

解决方案

第一步:云函数中正确捕获Puppeteer下载的CSV文件

不用依赖本地磁盘路径,直接监听Puppeteer的download事件获取文件流,核心代码逻辑:

const [download] = await Promise.all([
  page.waitForEvent('download'), // 等待下载触发
  page.locator('#download-btn').click() // 触发下载的操作,替换成你实际的点击元素
]);
// 直接获取文件缓冲区,不用写入本地磁盘
const csvBuffer = await download.createReadStream().then(stream => 
  new Promise((resolve, reject) => {
    const chunks = [];
    stream.on('data', chunk => chunks.push(chunk));
    stream.on('end', () => resolve(Buffer.concat(chunks)));
    stream.on('error', reject);
  })
);
// 也可以直接获取下载文件的默认文件名
const fileName = await download.suggestedFilename();

这种方式完全兼容无桌面的云函数环境,不需要依赖本地Drive同步客户端。

第二步:将CSV文件同步到Google Drive(AppScript可直接访问)

两种可选方案,选你熟悉的即可:

方案1:云函数直接调用Google Drive API上传

提前在Google Cloud控制台开通Drive API,获取服务账号密钥,给服务账号授权你的Drive目录写入权限,上传代码示例:

const { google } = require('googleapis');
const drive = google.drive({ version: 'v3', auth: yourAuthClient });
await drive.files.create({
  requestBody: {
    name: fileName,
    parents: ['你的Drive目标文件夹ID'] // 替换成你自己的文件夹ID
  },
  media: {
    mimeType: 'text/csv',
    body: csvBuffer // 直接用刚才捕获的文件缓冲区
  }
});

上传后的文件存在你的Drive目录里,AppScript可以直接通过DriveApp读取,和你之前本地同步的效果完全一致。

方案2:传入Google AppScript处理

如果需要走AppScript的逻辑处理,直接给AppScript部署一个Web应用,在云函数里把CSV缓冲区POST到AppScript的Web应用地址,AppScript端直接接收请求体写入Drive即可:
AppScript端核心代码:

function doPost(e) {
  const fileBlob = Utilities.newBlob(Utilities.base64Decode(e.postData.contents), 'text/csv', e.parameter.fileName);
  DriveApp.getFolderById('你的目标文件夹ID').createFile(fileBlob);
  return ContentService.createTextOutput(JSON.stringify({status: 'success'})).setMimeType(ContentService.MimeType.JSON);
}

定时执行配置

云函数侧直接配置定时触发器即可,主流云厂商的云函数产品都支持定时触发规则配置,无需本地值守运行。

内容的提问来源于stack exchange,提问作者ICV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:54:04