Node js 和浏览器:暂停和恢复文件下载

Ash*_*ram 5 browser node.js box

我正在使用 box.nodejs 在客户端下载文件。

我有一个盒子的网址。

当用户在浏览器中点击框 url 时,

https://www.example.com?url=https://box.com/file/123

我遵循的过程是:

在 Node js 中获取 box url 并向 box.com 发出请求

  const obj = urlParse.parse(fileUrl, true);
  const creq = https.request(obj, (cres) => {

  cres.setEncoding('utf8');

if (cres.statusCode === 200) {
  res.writeHead(cres.statusCode, 
    { 
      'Content-Type': 'application/octet-stream',
      'Content-Disposition' : cres.headers['content-disposition']
    }
  );
} else {
  res.writeHead(cres.statusCode, 
    { 
      'Content-Type': 'application/json'
    });
}

// wait for data
cres.on('data', function(chunk){
  res.write(chunk);
});

cres.on('close', function(){
  return res.end();
});

cres.on('end', function(){

  return res.end();
});

}).on('error', function(e) {
return res.end(e.message);
});

creq.end();
Run Code Online (Sandbox Code Playgroud)

我面临的问题是,在生产中,如果有时网络不好或生产速度不好 - 节点服务器,那么在浏览器中它会显示错误为“网络失败 - 服务器错误”

所以我想实现,当网络不好时暂停,如果网络好则恢复。

任何人都可以帮我处理这个问题吗?

流程是:

请求:浏览器 -> Node js -> Box.com 响应:Box.com -> Node js -> 浏览器(逐块获取文件数据)

如果网络不好,会出现网络故障的错误。

因此,如果网络不好,我需要暂停节点js和浏览器中的文件下载,当网络良好时,它将自动恢复浏览器和节点js中的下载。

因此,即使在网络不好的情况下,该文件也会得到下载,而不是向用户显示网络失败 - 服务器错误信息。