使用Node JS传输MP3文件时出现问题

时间:2019-07-22 17:00:20

标签: javascript node.js http server seek

首先,我的主要目标(除了流/发送mp3文件之外)是实现搜索。我已经可以在Firefox和IE上运行它,但不能在Chrome上运行。主要是,我检查了堕胎情况,Chrome总是提前中止。有什么需要确保不会发生的事情(即标头)?这是服务器逻辑:

function handler(req, res){
  const headers = req.headers;
  const targetArr = req.url.split('/');
  targetArr[0] = '.';
  const target = path.join(...targetArr);
  if ('range' in headers) {
    //Then a bunch of logic for handling the bytes range(s)
  } else {
    //Here is where chrome aborts
    //Then follows up with a byte-range request (Range: <0>-)
    //On abortion, I clean up the file stream and close the connection
    //However, in Chrome the request stays pending
    //Also, I made my own fsPromises.stat as it's experimental
    fsPromises.stat(target).then((stats)=>{//stats: fs.Stats
      res.writeHead(200, {
        'Content-Type': 'audio/mpeg',
        'Content-Length': stats.size,
        'Accept-Ranges': 'bytes'
      });
      fs.createReadStream(target).pipe(res);
    }).catch(()=>{
      //Error handling(like 404) here
    });
  }
}

0 个答案:

没有答案