Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

HowTo: Pipe only body to http.ServerResponse #314

Closed
berstend opened this Issue · 4 comments

3 participants

@berstend

Hi,
in the Readme you give the following example:

You can also pipe() from a http.ServerRequest instance and to a http.ServerResponse instance. The HTTP method and headers will be sent as well as the entity-body data. Which means that, if you don't really care about security, you can do:

http.createServer(function (req, resp) {
  if (req.url === '/doodle.png') {
    var x = request('http://mysite.com/doodle.png')
    req.pipe(x)
    x.pipe(resp)
  }
})

I'd like to use my own headers when doing this. Is there an easy way to only pipe the body / use custom headers?

Thanks.

@Marak

I don't think you easily can modify the body or headers without buffering the entire request into memory ( which somewhat defeats the purpose of using the stream api ).

You should be able to modify the request instance directly and then manually call res.write / res.end / etc..

@irrenhaus

You can set the pipefilter function on the request object:

request.get(url).pipefilter = function(response, dest) {};

The response object is the response itself, dest is the destination stream which you passed to the request.pipe(dest) function.

In the pipefilter you can now manipulate the headers:

var r = request.get(url)
r.pipefilter = function(response, dest) {
    var content_type = response.headers['content-type'];
    var content_length = response.headers['content-length'];
    for(var i in response.headers) {
      dest.removeHeader(i);
    }
    dest.setHeader('Connection', 'close');

    if(content_type)
      dest.setHeader('Content-Type', content_type)

    if(content_length)
      dest.setHeader('Content-Length', content_length)
  }
  var p = r.pipe(resp)
@Marak

Nice @irrenhaus! Didn't know that was added.

@berstend

Sweet, it works!
Thanks @Marak and @irrenhaus.

@berstend berstend closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.