在Express中发送响应后,如何删除zip文件

发布于 2025-02-11 17:48:07 字数 1117 浏览 1 评论 0原文

我只想在发送响应后删除zip文件夹,因此我正在寻找任何替代解决方案

,这是我的代码/获取请求

exports.Download = async (req, res) => {
       try {
        var zp = new admz();
        zp.addLocalFolder(`./download/${folder}`);
        const file_after_download = 'downloaded.zip';
        const data = zp.toBuffer();
        res.set('Content-Type', 'application/octet-stream');
        res.set('Content-Disposition', `attachment; filename=${file_after_download}`);
        res.set('Content-Length', data.length);
        return res.send(data);
        
        // HERE I want execute this code 
        let dir = `./download/${folder}`;
        if (fse.existsSync(dir)) {
            fse.rmdirSync(dir, { recursive: true })
        }
         
    } catch (err) {
        console.log(err)
        return res.render('pages/404');
    }
}

update

  1. 如果没有发送代码,没有return> return (res.send(data);) 我会遇到此错误//错误[err_http_headers_sent]:将标题发送到客户端//

    后无法设置标头
  2. 如果我将return res.send(data);在块末尾, 无法设置标头//

    然后下载的zip文件将为空 - 因为已删除已删除

I just want to delete zip folder after sent response so I am looking for any alternative solution

Here is my code / it is get request

exports.Download = async (req, res) => {
       try {
        var zp = new admz();
        zp.addLocalFolder(`./download/${folder}`);
        const file_after_download = 'downloaded.zip';
        const data = zp.toBuffer();
        res.set('Content-Type', 'application/octet-stream');
        res.set('Content-Disposition', `attachment; filename=${file_after_download}`);
        res.set('Content-Length', data.length);
        return res.send(data);
        
        // HERE I want execute this code 
        let dir = `./download/${folder}`;
        if (fse.existsSync(dir)) {
            fse.rmdirSync(dir, { recursive: true })
        }
         
    } catch (err) {
        console.log(err)
        return res.render('pages/404');
    }
}

Update

  1. If send code without return ( res.send(data);)
    Im getting this error //Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client //

  2. If I put return res.send(data); at the end of block , then downloaded zip file will be empty - because its deleted already

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

疯到世界奔溃 2025-02-18 17:48:07

来自 docs express,您可以使用res.download( )函数,该函数在下载完成后将执行回调参数。

res.download(filePath, 'yourFileName', function(err) {
  if (err) {
    next(err)
  } else {
    console.log('Delete:', filePath);
  }
})

From the docs of Express, you can use res.download() function which has a callback parameters to be executed once download is done.

res.download(filePath, 'yourFileName', function(err) {
  if (err) {
    next(err)
  } else {
    console.log('Delete:', filePath);
  }
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文