asynchronous - node.js: confusion with order of callbacks -
i have started node.js. find asynchronous coding style uses impressive indeed. however, of used java , python take time used it.
i know following code works fine. verified several questions on forum. have tried on own.
var http = require('http'), fs = require('fs'); fs.readfile('./index.html', function (err, html) { if (err) { //throw err; } http.createserver(function(request, response) { console.log("server started"); response.writeheader(200, {"content-type": "text/html"}); response.write(html); response.write("other things"); response.end(); }).listen(3000); });
the way interpretting follows:
1. try reading html file i. when done create server ii. send on client 2. else.
however, can have chain of thoughts follows:
1. create server 2. try reading file i. when done. send on client 3. in meanwhile else server might asked do.
the code corresponding second chain of thoughts is:
var http = require('http'), fs = require('fs'); http.createserver(function(request, response) { console.log("server started"); response.writeheader(200, {"content-type": "text/html"}); fs.readfile('./index.html', function (err, html) { if (err) { //throw err; } response.write(html); response.write("other things"); }); response.end(); }).listen(3000);
while first code works expected. second 1 displays nothing @ in browser.
why second chain of thoughts wrong?
actually, happens here following function gets called each time there incoming request:
function(request, response) { console.log("server started"); response.writeheader(200, {"content-type": "text/html"}); response.write(html); response.write("other things"); response.end(); }
you replaced with:
function(request, response) { console.log("server started"); response.writeheader(200, {"content-type": "text/html"}); fs.readfile('./index.html', function (err, html) { if (err) { //throw err; } response.write(html); response.write("other things"); }); response.end(); }
now here, run following:
- write header
- queue readfile
- immediately execute following:
response.end();
- by time done reading file , wants write contents, ended response
Comments
Post a Comment