Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

behavior of http.createServer #124

Closed
bfang-yseop opened this issue Dec 17, 2013 · 4 comments
Closed

behavior of http.createServer #124

bfang-yseop opened this issue Dec 17, 2013 · 4 comments

Comments

@bfang-yseop
Copy link

I am running through stream-adventure: http server when I first stumbled upon this oddity.

when I wrote my code like so:

var through = require('through');
var http = require('http');

var ts = through(function (buf){
    this.queue(buf.toString().toUpperCase());
})

var server = http.createServer(function (req, res) {


    if (req.method === 'POST'){
        req.pipe(ts).pipe(res);
    } else {
        res.end("Will I dream? \n")
    }
});

server.listen(process.argv[2])

I got extra results that I could not explain. However, when I moved var ts = ... into createServer's callback function the program ran as expected.

Can anyone explain what happened? Why would declaring ts outside of createServer produce different results?

@timoxley
Copy link

  • createServer's callback is fired for every new request.
  • the through stream is a queue.
  • declaring the through stream outside the createServer means all connections are sharing the same queue
  • a connection's response reads data from the shared queue (ts.pipe(res))
  • highly likely it will read data which was put in there by a different connection's request. (req.pipe(ts))

i.e. through has an internal buffer. The response is mangled because concurrent requests are reading from the same buffer.

@bfang-yseop
Copy link
Author

I see, that makes sense. Thanks for the reply.

@timoxley
Copy link

👍

@relaxedtomato
Copy link

@timoxley thanks for clarifying this concept 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants