3

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?

Ben Mordue
  • 476
  • 8
  • 20

2 Answers2

4

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
    }
});
Ben Mordue
  • 476
  • 8
  • 20
3

You can read the header before stream starts if you want to.

var needle = require('needle');
var url = 'http://www.stackoverflow.com';

    needle.head(url, {method: 'HEAD'}, function (err, response) {
        if (!err && response.statusCode == 200) {
            console.log((JSON.stringify(response.headers)));
        }

    });

Or in Request

var request = require('request');
var url = 'http://www.stackoverflow.com';

request(url, {method: 'HEAD'}, function (err, response) {
    if (!err && response.statusCode == 200) {
        console.log((JSON.stringify(response.headers)));
    }    
});

Otherwise you can read it after stream.

var needle = require('needle');
var url = 'http://www.stackoverflow.com';

var stream = needle.get(url, function (err, response) {
    if (!err && response.statusCode == 200)
    console.log((JSON.stringify(response.headers)));
});

But this is also valid for request.

var request = require('request');
var url = 'http://www.stackoverflow.com';

var stream = request.get(url, function (err, response) {
    if (!err && response.statusCode == 200)
    console.log((JSON.stringify(response.headers)));
});
vineetv2821993
  • 927
  • 12
  • 25
  • Thank you for your answer, which is detailed and clearly laid out. However, the first two snippets make an extra HEAD request, which is not the same thing as getting the headers for a given request. The second two effectively revert to the callback model, which isn't really what I was looking for either. – Ben Mordue Jan 27 '16 at 20:24