5 javascript for-loop stream http2
for-loop?我push-stream通过读取.json配置文件尝试循环中的HTTP/2资源.如果只有一个资源resurce.file,type,则推送成功.如果配置中有多个资源,则仅推送列出的第一个资源,并且不推送其余资源,客户端永远不会接收剩余文件,也不会完成解析.
我想只有第一个资源流结束,剩下的开放流没有关闭.
我最好评论代码应该正常运行:
// Verify if client can be pushed to:
if (res.push) {
// Read what resources should be pushed via config.json5:
for(var i = 0; i < confg.resource.length; i++) {
// Compare what URL requested the resources & pass the relevant files:
if (req.url == confg.resource[i].url) {
// Request the resource(s) to stream:
var ps = fs.readFileSync('../build' + confg.resource[i].file)
// Push the relevant resource stream(s):
, stream = res.push(confg.resource[i].file
, { // ..and set the content type;
res: {'content-type': confg.resource[i].type},
});
// Close the resource stream(s):
stream.end(ps, function() {
// TODO(CelticParser): Remove for production ->v
console.log("Pushed Sream");
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
.config.json5:
resource: [ // HTTP/2 Push-Streams
{ file: '/js/theme.min.js',
type: 'script'
},
{ file: '/css/theme.min.css',
type: 'style',
url: '/'
}
]
Run Code Online (Sandbox Code Playgroud)
使用上面的例子;
如果/js/theme.min.js首先列出并且/css/theme.min.css在配置中列出第二个,/js/theme.min.js则将由浏览器加载,而另一个文件将不会加载并且客户端挂起(不会继续解析).如果交换资源的列表顺序,则会发生相同的事情.如果配置中只列出了一个文件,则一切都按预期工作.
任何帮助将不胜感激.
问题出在config.json5. 在将文件传递到此处之前,您将检查请求的 url:
// Compare what URL requested the resources & pass the relevant files:
if (req.url == confg.resource[i].url) {
...
}
Run Code Online (Sandbox Code Playgroud)
但在您的 json 中,只有一项可以通过测试,另一项缺少该url属性。将您的配置更改为此(添加url: '/'到第一项),它将起作用:
{
resource : [
{
file : '/js/theme.min.js',
type : 'script',
url : '/'
},
{
file : '/css/theme.min.css',
type : 'style',
url : '/'
}
]
}
Run Code Online (Sandbox Code Playgroud)
按照http2 服务器示例以及您的服务器代码使用这个小应用程序进行了测试。
服务器.js
var fs = require("fs");
var path = require("path");
var http2 = require("http2");
var config = require("./config.json");
var options = {
key : fs.readFileSync("./localhost.key"),
cert : fs.readFileSync("./localhost.crt")
};
//----------------------------------------------------
http2.createServer(options, function(req, res) {
if (res.push) {
config.resource.forEach(function(resource){
if (req.url === resource.url) {
var push = res.push(resource.file, { res: {"content-type": resource.type } });
push.writeHead(200);
fs.createReadStream(path.join("../build", resource.file)).pipe(push);
}
});
}
res.writeHead(200);
res.end();
}).listen(8080);
Run Code Online (Sandbox Code Playgroud)
该config.json文件包含上述更正的配置。
输出:
// Compare what URL requested the resources & pass the relevant files:
if (req.url == confg.resource[i].url) {
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
190 次 |
| 最近记录: |