2017-03-16 5 views
1

リクエストnpmモジュールを使用してリクエストを作成しています。しかし、コンテンツタイプがjsonでない場合は、ストリームを停止します。現時点では停止せず、unzipが無効なヘッダーを読み取るためエラーが生成されます。ストリームを停止するにはどうすればよいですか?Node.js:ストリーミングデータからパイプを停止する方法

var req = request(options) 
    req 
    .on('error', function (err) { console.log("err"); reject(err) }) 
    .on('response', function(response) { 

     if(response.headers['content-type'] != 'application/json') 
     { 
      console.log(response.headers['content-type']) 
      req.destroy() // doesn't work 
      this.destroy() // doesn't work 
     } 
    }) 
    .on('end', function() { resolve() }) 

    .pipe(gunzip) // ERROR! 
+0

は、if文でresponse.headers [ 'コンテンツタイプを']ログインこのコードはありますか? –

+0

代わりに 'response.end()'や 'req.end()'を試したことがありますか? – Kristian

+0

response.end()は関数ではなく、req.end()は機能しません。 –

答えて

2

次のようにstream.pause()を使用することができます。

var req = request(options) 
req 
    .on('error', function (err) { console.log("err"); reject(err) }) 
    .on('response', function(response) { 

    if(response.headers['content-type'] != 'application/json') 
    { 
     console.log(response.headers['content-type']) 

     req.pause(); // stream paused 
     reject('not json'); 
    } 
    }) 
    .on('end', function() { resolve() }) 
    .pipe(gunzip) 
関連する問題