学习音视频的过程中为了搭建本地服务器稍微学习了node js,由于之前弄过微信小程序,上手起来还是比较快的。
const express = require('express')
const fs = require('fs')
const path = require('path')
const app = express()
app.use(express.static(path.join(__dirname, 'public')))
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.htm'))
})
app.get('/video', function(req, res) {
const fileName = req.query.name
const path = fileName + ".mp4"
const stat = fs.statSync(path)
const fileSize = stat.size
const range = req.headers.range
if (range) {
const parts = range.replace(/bytes=/, "").split("-")
const start = parseInt(parts[0], 10)
const end = parts[1]
? parseInt(parts[1], 10)
: fileSize-1
const chunksize = (end-start)+1
const file = fs.createReadStream(path, {start, end})
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
}
res.writeHead(206, head)
file.pipe(res)
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': 'video/mp4',
}
res.writeHead(200, head)
fs.createReadStream(path).pipe(res)
}
})
app.listen(3000, function () {
console.log('Listening on port 3000!')
})
使用时,新建一个文件夹,将视频文件和js文件放该目录下,然后 node server.js 运行脚本,使用 http://localhost:3000/video?name=123 类似的方式进行请求即可。如果报错,使用npm install [package]安装缺省的包!