使用NodeJS和HapiJS进行视频流

问题描述

我想使用NodeJS而不是Express使用HapiJs流视频文件

这是我想使用HapiJS实现的目标

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)完全做到这一点?

解决方法

找到了解决方案:

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
    }
]

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...