Thursday 22 June 2017

Why does setting an error listener after piping a stream work?

Hey /r/node,I'm currently reading "Node.js in Action", and one of the chapters is having me write a static file server. We create a read stream from the requested path, pipe it to the response object, and then set an error listener.var server = http.createServer(function(req, res){ var url = parse(req.url) var path = join(root, url.pathname) var stream = fs.createReadStream(path) stream.pipe(res) stream.on('error', function(err){ res.statusCode = 500 res.end('Internal server error') }) }) I'm having trouble wrapping my head around why its possible to set the error listener after piping the the read stream to the response stream. If i request a file that doesn't exist, an error event is emitted as soon as 'createReadStream(path)' starts. At this point, we haven't set an error listener for the stream yet, so why does this work?My only explanation is that since createReadStream is asynchronous, that the error listener gets set before it emits an error event. If that's the case, isn't this bad code? Isn't there like a race condition between the error in createReadStream and setting the error listener? Is it not possible for the error to be emitted before the program gets around to setting the listener?

Submitted June 22, 2017 at 11:01PM by bskilly

No comments:

Post a Comment