如何在for-loop中关闭流?

我正在尝试通过读取push-stream配置文件在循环内使用HTTP/2资源.json。如果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");
      });
    }
  }
}

.config.json5:

resource: [ // HTTP/2 Push-Streams
  { file: '/js/theme.min.js',
     type: 'script'
  },
  { file: '/css/theme.min.css',
    type: 'style',
    url:  '/'
  }
]

使用上面的示例;

如果在配置中首先列出了/js/theme.min.js,然后列出了/css/theme.min.css,则/js/theme.min.js将由浏览器加载,其他文件将不加载,并且客户端挂断(不再继续解析)。如果交换资源的列表顺序,则会发生相同的情况。如果配置中仅列出了一个文件,则一切正常。

任何帮助将不胜感激。

最佳答案

问题出在config.json5中。您正在检查请求的网址,然后再在此处传递文件:

// Compare what URL requested the resources & pass the relevant files:
if (req.url == confg.resource[i].url) {
   ...
}

但是在您的json中,只有一项可以通过测试,而另一项则缺少url属性。将您的配置更改为此(将url: '/'添加到第一项),它将起作用:
{
   resource : [
      {
         file : '/js/theme.min.js',
         type : 'script',
         url  :  '/'
      },
      {
         file : '/css/theme.min.css',
         type : 'style',
         url  :  '/'
      }
   ]
}

http2 server example之后,使用此小型应用程序进行了测试,还使用了服务器代码进行了测试。

server.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);
config.json文件包含上述经过更正的配置。

输出:

Receiving pushed resource: ./js/bootstrap.min.js -> /Developer/so/tests/push-0
Receiving pushed resource: ./css/bootstrap.min.css -> /Developer/so/tests/push-1

关于javascript - HTTP/2 : stream.使用循环结束,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34193374/

10-12 12:53
查看更多