nodejs实现大文件(在线视频)的读取
2019/6/27 20:31:26
本文主要是介绍nodejs实现大文件(在线视频)的读取,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
nodejs进行视频读取时不能像读取图片之类的一次性读取,而是必须读取一部分返回一部分,这样客户端的播放才会边缓冲边播放,而不必等待全部缓冲完再播放。
老规矩,直接贴代码讲解:
var fs = require('fs'); function readBigFileEntry(filename, response) { path.exists(filename, function(exists) { if (!filename || !exists) { response.writeHead(404); response.end(); return; } var readStream = fs.ReadStream(filename); var contentType = 'none'; var ext = path.extname(filename); switch (ext) { case ".flv": contentType = "video/flv"; break; } response.writeHead(200, { 'Content-Type' : contentType, 'Accept-Ranges' : 'bytes', 'Server' : 'Microsoft-IIS/7.5', 'X-Powered-By' : 'ASP.NET' }); readStream.on('close', function() { response.end(); console.log("Stream finished."); }); readStream.pipe(response); }); }
通过fs模块的ReadStream方法,拿到视频流,然后绑定关闭事件:当流读取到结尾的时候结束response请求,最后通过pipe方法进行小块小块的读取。这里的head信息不能添加Content-Length属性,因为必须分段读取,如果加了这个属性,浏览器就会以为请求结束了从而关闭请求。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。
这篇关于nodejs实现大文件(在线视频)的读取的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-30React Native常用组件-点击组件
- 2024-05-30uniapp+vue3+uv-ui手机端后台OA管理模板
- 2024-05-29Python网络爬虫的时候json=就是让你少写个json.dumps()
- 2024-05-27React Native常用组件-展示组件
- 2024-05-27React Native常用组件-列表组件
- 2024-05-09vue3开发前端表单缓存自定义指令,移动端h5必备插件
- 2024-05-09React Hooks在class组件中的使用方式
- 2024-03-30[OIDC in Action] 2. 基于OIDC(OpenID Connect)的SSO(纯JS客户端)
- 2024-03-29terraform jsonencode
- 2024-03-13vuex-persist