节点JS请求+快速pipe道

我有一个从服务器到另一个videostream文件的问题。

我写了这个脚本

var request = require("request"), express = require("express"); var app = express(); app.get("/cast", function(req, res) { var url = req.query.video; res.writeHead(200, { 'Content-Type': 'video/mp4' }); request({ url: url, headers: { Referer: "http://example.com/1706398/" + url } }) .on('response', function(response) { response.on('data', function(data) { console.log("data chunk received: " + data.length) }); response.on('end', function(data) { console.log('Video completed'); }); }) .pipe(res); }); app.listen(8080); 

但是,有时video响应有时会损坏,而如果请求的数据被写入一个可写的缓冲区,并保存为video文件,它可以处理任何url。 我找不到任何错误或问题在我的代码,在这里一些url:

这里有一些我试过的url: https : //gist.github.com/FrancisCan/f2bb86f8ff73b45fa192

谢谢 :)

删除writeHead 200,当你正在stream媒体的时候,你应该返回http 206结果(部分内容),而不是http200。 我有和你一样的场景(将video文件从云中的blob容器传输到angular度应用程序),不需要http200响应。

更新:添加一些代码,我如何做到这一点:

 AzureStorageHelper.prototype.streamBlob = function streamBlob(req, res, blob, params) { if(!params){ params.container = container; } blob_service.getBlobProperties(params.container, blob, function (error, result, response) { if(!result) return res.status(404).end(); if(error) return res.status(500).end(); var blobLength = result.contentLength; var range = req.headers.range ? req.headers.range : "bytes=0-"; var positions = range.replace(/bytes=/, "").split("-"); var start = parseInt(positions[0], 10); var end = positions[1] ? parseInt(positions[1], 10) : blobLength - 1; var chunksize = (end - start) + 1; var options = { rangeStart: start, rangeEnd: end, } //this is what's interesting for your scenario. I used to set this up myself but it's is now handled by the Azure Storage NodejsSDK /*res.writeHead(206, { 'Accept-Ranges': 'bytes', 'Content-Range': "bytes " + start + "-" + end + "/" + blobLength, 'Content-Type': result.contentType, 'Content-Length': chunksize, 'Content-MD5': result.contentMD5, });*/ var options = { rangeStart: start, rangeEnd: end, } //this is an API from the Azure Storage nodejsSDK I use. You might want to check the source of this method in github to see how this lib deals with the http206 responses and the piping blob_service.getBlobToStream(params.container, blob, res, options, function (error, result, response) { if (error) { return res.status(500).end(); } }); });