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

NodeJS调用Google Drive API下载文件时如何取消后端下载进程

实现方式

问题核心成因:

  1. res.close事件监听被放在data事件回调内,每次收到数据块都会重复绑定监听器,最终导致内存溢出或程序异常
  2. 仅终止了返回前端的响应,未销毁Google Drive API返回的下载流,后端会持续从Google服务器拉取数据直到任务完成

修改后的代码如下:

try {
    const auth = await autenticacion();
    const drive = google.drive({ version: 'v3', auth });

    drive.files.get(
        { fileId, alt: 'media' },
        { responseType: 'stream' },
        ((err, respuesta) => { 
            if(err) {
                console.log(err);
                return res.end();
            }
            const driveDownloadStream = respuesta.data;
            
            // 外层监听前端断开事件,直接销毁Google Drive下载流
            res.on('close', () => {
                if (!driveDownloadStream.destroyed) {
                    driveDownloadStream.destroy();
                }
                if (!res.writableEnded) {
                    res.end();
                }
            });

            driveDownloadStream
            .on('end', () => {
                res.end()
            })  
            .on('error', err => {
                console.log('下载异常:', err);
                if (!res.writableEnded) {
                    res.end()
                }
            })  
            .pipe(res);
        })
    )
} catch (error) {
    console.log(error)
}

优化点说明

  • 移除data事件内的重复监听逻辑,将请求关闭监听放在流初始化完成后的外层,避免重复绑定
  • 前端取消请求触发res.close事件时,主动调用destroy()销毁Google Drive下载流,直接终止API传输任务
  • 用pipe方法处理流传输,自动处理背压、数据写入、结束逻辑,比手动监听data事件写入响应稳定性更高
  • 所有操作前先判断流和响应的状态,避免重复调用方法抛出异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:33:01