Node.js: How to stop a pipe from streaming data

368
March 17, 2017, at 03:23 AM

I'm creating a request using the request npm module. However in case the content type is not json, i want the stream to stop. At the moment, it does not stop and and error is generated because unzip reads an invalid header.. How can we stop a stream?

    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!
Answer 1

you can use stream.pause() as follows:

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)
READ ALSO
Nginx: Proxy connection between client and an API connection

Nginx: Proxy connection between client and an API connection

I want to use Shutterstock API in my website, but access it via my country's IPs is not possible;

338
Database Connection security in nodejs

Database Connection security in nodejs

When I'm connecting to database in node, I have to add db name, username, password etcIf I'm right every user can access js file, when he knows address

240
Boostrap Table How to add commas between numbers

Boostrap Table How to add commas between numbers

Hi Have the following code which populates bootstrap table

198
remove all white spaces in media query navigation bar

remove all white spaces in media query navigation bar

I created a media query for phones with 414px width size and less or iPhone 6 plus "portrait"I am trying to make a drop down menu and I got everything to work, its just the navigation bar is not moving

216