javascript - Efficient closure structure in node.js -
i'm starting write server in node.js , wondering whether or not i'm doing things right way...
basically structure following pseudocode:
function processstatus(file, data, status) { ... } function gotdbinfo(dbinfo) { var myfile = dbinfo.file; function gotfileinfo(fileinfo) { var contents = fileinfo.contents; function sentmessage(status) { processstatus(myfile, contents, status); } sendmessage(myfile.name + contents, sentmessage); } checkfile(myfile, gotfileinfo); } checkdb(query, gotdbinfo);
in general, i'm wondering if right way code node.js, , more specifically:
1) vm smart enough run "concurrently" (i.e. switch contexts) between each callback not hung lots of connected clients?
2) when garbage collection run, clear memory if last callback (processstatus) finished?
node.js event-based, codes handlers of events. v8 engine execute-to-end synchronous code in handler , process next event.
async call (network/file io) post event thread blocking io (that's in
libev
libeio
afaik, may wrong on this). app can handle other clients. when io task done, event fired , callback function called upon.here's example of aync call flow, simulating node app handling client request:
onrequest(req, res) { // have io , cpu intensive task before responding client asynccall(function callback1() { // callback1() trigger after asynccall() done it's part // *note other code might have been executed in between* moreasynccall(function callback2(data) { // callback2() trigger after moreasynccall() done it's part // note other code might have been executed in between // res in scope closure res.end(data); // callback2() returns here, node can execute other code // client should receive response // tcp connection may kept alive though }); // callback1() returns here, node can execute other code // have done processing of asynccall() synchronously // in callback1(), block long // used moreasynccall() *yield other code* // kind of cooperative scheduling }); // tasks scheduled calling asynccall() // onrequest() returns here, node can execute other code }
when v8 not have enough memory, garbage collection. knows whether chunk of memory reachable live javascript object. i'm not sure if aggressively clean memory upon reaching end of function.
references:
this google i/o presentation discussed gc mechanism of chrome (hence v8).
http://platformjs.wordpress.com/2010/11/24/node-js-under-the-hood/
Comments
Post a Comment