2017-03-16 56 views
1

我创建使用请求NPM模块请求停止管道。但是,如果内容类型不是json,我希望流停止。目前,它不会停止,并产生错误,因为解压读到一个无效头.. 我们怎样才能阻止流?的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

此代码记录了response.headers [ '内涵式'] if语句? –

+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)