如何创建一个简单的HTTP服务器,监听3000端口以提供视频服务

如何创建一个简单的HTTP服务器,监听3000端口以提供视频服务

我们可以使用nodeJS和内置的nodeJS文件系统“fs”,借助于“express”来向浏览器/前端提供视频。在网页上观看视频,我们将使用HTML视频标签。我们将使用express进行路由设置。通过创建读取流并将res对象连接到它,我们将发送视频字节。让我们一步一步地来。

步骤1: 创建一个“app.js”文件并用npm初始化项目。另外,将要流式传输的视频文件放在同一个文件夹中。

npm init

步骤2: 现在安装express并创建“ index.html ”文件。

npm install express

项目结构: 它将如下所示。

如何创建一个简单的HTTP服务器,监听3000端口以提供视频服务

这里“ Welcome-To-GeeksforGeeks.mp4 ”是我们要流式传输的mp4文件。

步骤3: 现在让我们来编写“ app.js ”文件。 GET请求发送到‘ /stream ’将视频作为可读流发送。 应用程序的根目录加载“index.html”文件。 我们使用res.writeHead()函数将状态消息设为200,表示OK,并将内容类型设为mp4 / video。 现在我们将使用fs.createReadStream()函数创建一个读取流,将视频作为可读流发送到HTML视频标签。

app.js

// Requiring express for routing 
const express = require('express') 
  
// Creating app from express 
const app = express() 
  
// Requiring in-built file system 
const fs = require('fs') 
  
// GET request which HTML video tag sends 
app.get('/stream',function(req,res){ 
  
    // The path of the video from local file system 
    const videoPath = 'Welcome-To-GeeksforGeeks.mp4'
  
    // 200 is OK status code and type of file is mp4 
    res.writeHead(200, {'Content-Type': 'video/mp4'}) 
  
    // Creating readStream for the HTML video tag 
    fs.createReadStream(videoPath).pipe(res) 
}) 
  
// GET request to the root of the app 
app.get('/',function(req,res){ 
  
    // Sending index.html file for GET request 
    // to the root of the app 
    res.sendFile(__dirname+'/index.html') 
}) 
  
// Creating server at port 3000 
app.listen(3000,function(req,res){ 
    console.log('Server started at 3000') 
})

步骤4: 现在我们将编写“ index.html ”文件。在这里,我们使用 controls 属性为视频标签提供各种控件。而 autoplay 是一个布尔属性,视频会在加载数据的同时开始自动播放。HTML视频标签的 src 属性是在app.js文件中定义的“/stream”。

index.html

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8" /> 
    <meta http-equiv="X-UA-Compatible"
        content="IE=edge" /> 
    <meta name="viewport" content= 
        "width=device-width, initial-scale=1.0" /> 
    <title>Video Stream</title> 
</head> 
  
<body> 
    <!--  autoplay: A Boolean attribute; if  
        specified, the video automatically  
        begins to play back as soon as it can  
        do so without stopping to finish  
        loading the data -->
  
    <video controls autoplay width="500px" height="500px"> 
          
        <!-- GET request to the stream route -->
        <source src="/stream" type="video/mp4" /> 
    </video> 
</body> 
  
</html> 

步骤5: 现在使用以下方式运行应用程序

node app.js

输出: 前往浏览器并输入 http://localhost:3000/

如何创建一个简单的HTTP服务器,监听3000端口以提供视频服务

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程