Search code examples
node.jsneedle.js

How to get response headers when using needle.js in streaming mode?


I want to use the needle module for node.js in streaming mode, similar to this example from the needle docs:

var stream = needle.get('http://www.as35662.net/100.log');

stream.on('readable', function() {
  var chunk;
  while (chunk = this.read()) {
    console.log('got data: ', chunk);
  }
});

This allows me to read the response body from the stream.

How can I access the response headers?


Solution

  • From reading the source, needle emits two events, header and headers.

    Interested in headers only:

    var stream = needle.get(someURL);
    
    stream.on('headers', function(headers) {
        // do something with the headers
    });
    

    or status code and headers:

    stream.on('header', function(statusCode, headers) {
        if (statusCode != 200) {
            // scream and panic
        }
    });