Reputation: 2945
I'm reading Node.js in Action. There is an example for a simple static file server, as follows:
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');
});
});
My question is, what happens if the stream.pipe() call hits an error BEFORE the 'error' handler is added to the stream? Could it "miss" this error?
Thanks!
Upvotes: 2
Views: 43
Reputation: 203494
When you write stream.pipe(res)
, it doesn't mean that streaming will start right at that line, it will just be scheduled to run once the code in the request handler is done (Node runs code in a single thread, so it can do only one thing at a time).
After the request handler is done, control is yielded back to the internal Node event loop, which will check to see if there is any I/O to be performed, like handling your stream. At that time, the error
handler is already in place to handle any errors.
Upvotes: 4