【问题标题】:About Node Google Drive API关于 Node Google Drive API
【发布时间】:2025-11-29 01:05:02
【问题描述】:

目前我正在使用NodeJS的google drive api,这是我用来下载文件的代码

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);
                res.end();
            }
            respuesta.data
            .on('end', () => {
                res.end()
            })  
            .on('error', err => {
                res.end()
            })  
            .on('data', d => {
                res.write(d)
                //the next line below i'm trying to cancel the download but gives me an exception an the programm breaks
                res.on('close', da => {
                    res.end();
                })
            });
            

        })
    )
    
    
} catch (error) {
    console.log(error)
    
}

我想要实现的也是取消当前下载,我正在使用 angular

this.descargaActual.unsubscribe();

当我试图取消单击按钮的下载时,在前端下载会停止,但在后端进程中,文件仍在下载中。 就像我在代码中的评论中提到的那样,它给了我一个例外

有没有办法从节点取消当前在 google drive api 中的下载?

【问题讨论】:

    标签: node.js angular api express google-drive-api


    【解决方案1】:

    要取消下载,我会尝试销毁从 Drive API 获得的可读流。否则,只需将该流通过管道传输到响应对象中。

    res.on("close", function() {
      respuesta.data.destroy();
    });
    respuesta.data.pipe(res);
    

    【讨论】: