node返回mp4视频流且可拖动

679 阅读1分钟

这两天做了个项目需要播放自动化测试的视频,把文件成功保存到机器上了,但是怎么展示代码如下:

const stats = statSync(videoPath)
const range = (req.headers as any).range
const positions = range.replace(/bytes=/, '').split('-')

const start = parseInt(positions[0], 10)
const total = stats.size
const end = positions[1] ? parseInt(positions[1], 10) : total - 1
const chunksize = end - start + 1

// Content-Range很重要,格式不能错,bytes和start之间有个空格。
res.writeHead(206, {
  'Content-Range': `bytes ${start}-${end}/${total}`,
  'Accept-Ranges': `bytes`,
  'Content-Length': chunksize,
  'Content-Type': `video/mp4`
})

const file = createReadStream(videoPath, { start, end })
file.pipe(res)

完结撒花