Note that there are some explanatory texts on larger screens.

plurals
  1. POnode.js - attaching event handlers on time
    primarykey
    data
    text
    <p>I'm studying node.js and came across this example in the node.js manual:</p> <pre><code>... var req = http.request(options); req.end(); req.on('upgrade', function(res, socket, upgradeHead) { console.log('got upgraded!'); socket.end(); process.exit(0); }); ... </code></pre> <p>What I see in this example is that handler attached to an event of HTTP request, <em>after</em> the request is created and even <em>after it is (scheduled to be) sent</em>. To make things even worse, manuals says:</p> <blockquote> <p>If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.</p> </blockquote> <p>Isn't it possible for the event to occur <strong>before</strong> <code>req.on(...</code> had a chance to attach a handler ? I suspect I don't understand something in node's asynchronous model. Or this code from node manual designed in hope that network request will take longer than executing next line of code ?!</p> <p>Another example:</p> <pre><code>http.get("http://www.google.com/index.html", function(res) { console.log("Got response: " + res.statusCode); }).on('error', function(e) { console.log("Got error: " + e.message); }); </code></pre> <p>Here, HTTP request will be initiated immediately after the object created, and we attach an error handler only afterwards. Again, (1) is it a code that works only because of network latencies, (2) I don't get something about node.js concepts, or (2b) event will "wait" until I attach a handler to it ?</p> <p><strong>EDIT</strong>: Even better example, also from manual. <em>Good</em> and <em>Bad</em> examples below are different only because in the good one we attach the event quick enough and thus have <strong>low chances</strong> to miss data, or it is <strong>never possible to miss data</strong> this way (and why ?!)</p> <pre><code>// Good request.on('response', function (response) { response.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); // Bad - misses all or part of the body request.on('response', function (response) { setTimeout(function () { response.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }, 10); }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload