10

したがって、この(簡略化された)コードでは、誰かが私のノードサーバーにアクセスしたときに、別のWebサイトにGETリクエストを送信し、HTMLページのタイトルをコンソールに出力します。正常に動作します:

var http = require("http");
var cheerio = require('cheerio');

var port = 8081;
s = http.createServer(function (req, res) {
var opts = {
    method: 'GET',
    port: 80,
    hostname: "pwoing.com",
    path: "/"
};
http.request(opts, function(response) {
    console.log("Content-length: ", response.headers['content-length']);
    var str = '';
    response.on('data', function (chunk) {
        str += chunk;
    });
    response.on('end', function() {
        dom = cheerio.load(str);
        var title = dom('title');
        console.log("PAGE TITLE: ",title.html());
    });
}).end();
res.end("Done.");
}).listen(port, '127.0.0.1');

ただし、実際のアプリでは、ユーザーはヒットするURLを指定できます。つまり、私のノードサーバーは20GBの映画ファイルなどをダウンロードしている可能性があります。良くない。content-lengthヘッダーは、すべてのサーバーによって送信されるわけではないため、これを停止するのにも役立ちません。次に質問:

たとえば、最初の10KBを受信した後、GET要求を停止するように指示するにはどうすればよいですか?

乾杯!

4

1 に答える 1

15

十分なデータを読み取ったら、リクエストを中止できます。

  http.request(opts, function(response) {
    var request = this;
    console.log("Content-length: ", response.headers['content-length']);
    var str = '';
    response.on('data', function (chunk) {
      str += chunk;
      if (str.length > 10000)
      {
        request.abort();
      }
    });
    response.on('end', function() {
      console.log('done', str.length);
      ...
    });
  }).end();

データはさまざまなサイズのチャンクで到着するため、これにより10.000バイトでリクエストが中止されます。

于 2013-03-26T11:57:26.707 に答える