参考:https://blog.csdn.net/liuyaqi1993/article/details/76560401
Readable Stream:可读流是对可消费的数据源进行的抽象,比如fs.createReadStream Writable Stream:可写流是对流的目的地(destination)的抽象,destination运允许数据写入,比如fs.createWriteStream Duplex Stream:双工流是同时实现了 Readable 和 Writable 接口的流,既能写又能读。比如TCP socket Transform Stream:交换流本质上是一种Duplex流,可以将其看成输入Writable流,输出的是Readable流,也可以称之为“通过流”(through streams)。比如zlib streams。
文件流
var http = require("http");
var fs = require("fs");
var server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "image/png",
"Access-Control-Allow-Origin": "*",
});
if (req.url == "/fang") {
res.end("fang");
} else if (req.url == "/yuan") {
res.end("yuan");
} else {
fs.readFile("./1.mp4", "binary", function (err, file) {
if (err) {
console.log(err);
return;
} else {
res.write(file, "binary");
res.end();
}
});
}
});
server.listen(3000, "127.0.0.1", (res) => {
console.log("http://127.0.0.1:3000/");
});
视频流
var fs = require("fs");
var express = require("express");
var router = express();
router.get("/video", function (req, res, next) {
let head = { "Content-Type": "video/*" };
res.writeHead(200, head);
fs.createReadStream("./1.mp4").pipe(res);
});
router.listen(3000);
分段流
var fs = require("fs");
var express = require("express");
var router = express();
router.get("/video", function (req, res, next) {
let path = "./1.mp4";
let stat = fs.statSync(path);
let fileSize = stat.size;
let range = req.headers.range;
if (range) {
let parts = range.replace(/bytes=/, "").split("-");
let start = parseInt(parts[0], 10);
let end = parts[1] ? parseInt(parts[1], 10) : start + 999999;
end = end > fileSize - 1 ? fileSize - 1 : end;
let chunksize = end - start + 1;
let file = fs.createReadStream(path, { start, end });
let 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 {
let head = {
"Content-Length": fileSize,
"Content-Type": "video/mp4",
};
res.writeHead(200, head);
fs.createReadStream(path).pipe(res);
}
});
router.listen(3000);
前端
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
body {
background: black;
color: #CCCCCC;
}
#c2 {
background-image: url('foo.png');
background-repeat: no-repeat;
}
div {
float: left;
border: 1px solid #444444;
padding: 10px;
margin: 10px;
background: #3B3B3B;
}
</style>
</head>
<body>
<div>
<video id="video" src="http://127.0.0.1:3000/video" controls="true" />
</div>
<div>
<canvas id="c1" width="160" height="96" />
<canvas id="c2" width="160" height="96" />
</div>
<script src="index.js"></script>
<script>
processor.doLoad()
</script>
</body>
</html>
|