首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用NodeJS和HapiJS进行视频流传输

使用NodeJS和HapiJS进行视频流传输
EN

Stack Overflow用户
提问于 2020-09-08 22:01:43
回答 1查看 57关注 0票数 0

我想使用NodeJS来流式传输视频文件,但使用的是HapiJs而不是Express。

以下是我希望使用HapiJS实现的目标

代码语言:javascript
复制
const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();

app.use(express.static(path.join(__dirname, 'public')));

const videoFilePath = path.join(__dirname, 'vid.mp4');
const fileSize = fs.statSync(videoFilePath).size;

app.get('/video', (req, res) => {
  const { range } = req.headers;
  const [s, e] = range.replace('bytes=', '').split('-');
  const start = Number(s);
  const end = Number(e) || fileSize - 1;
  res.append('Accept-Ranges', 'bytes');
  res.append('Content-Range', `bytes ${start}-${end}/${fileSize}`);
  res.append('Content-Length', end - start + 1);
  res.append('Content-Type', 'video/mp4');
  res.status(206);
  const fileStream = fs.createReadStream(videoFilePath, { start, end });
  fileStream.pipe(res);
});

app.listen(3000, () => {
  console.log('Server is up...');
});

我该如何使用HapiJS (版本大于17)来做到这一点呢?

EN

回答 1

Stack Overflow用户

发布于 2020-09-09 16:12:08

找到解决方案:

代码语言:javascript
复制
const fs = require("fs")
const Path = require("path");

downloadFile = async (request, h) => {
    try {
        const path = Path.join(__dirname, `../../path`)
        const { size } = fs.statSync(path)
        const { range } = request.headers
        const start = Number((range || '').replace(/bytes=/, "").split("-")[0])
        const end = size - 1
        const chunkSize = (end - start) + 1
        const stream = fs.createReadStream(path, { start, end })
        return h.response(stream)
            .type("video/mp4")
            .header("Pragma", "no-cache")
            .header("Cache-Control", "public, must-revalidate, max-age=0")
            .header("Content-Range", `bytes ${start}-${end}/${size}`)
            .header("Accept-Ranges", "bytes")
            .header("Content-Length", chunkSize)
            .header("Content-Description", 'File Transfer')
            .header("Content-Disposition", `attachment; filename=${request.params.filename};`)
            .header("Content-Transfer-Encoding", "binary")
    }
    catch (err) {
        console.log(err)
    }
}

module.exports = [

{
        method: "GET",
        path: "/api/url/endpoint/{filename}",
        handler: downloadFile
    }
]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63795585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档