I've been struggling with this for a week now, and I have read dozens upon dozens of articles and posts related to callbacks, some of them over and over again. I still do not understand - at least for what I'm trying to do.
function rFile(dIn, callback){ // 4.
fs.readFile(dIn,function(err,dOut){
if(!err){
console.log('rFile OUT: '+dOut+' B Size: '+dOut.length);
} else {
console.log('rFile ERR: '+err);
};
callback(dOut);
});
}
function getRtn(dOut){ // 3.
console.log('getRtn OUT: '+dOut);
rtn = dOut;
return dOut;
};
function sendPage() { // 2.
rFile('index.htm', getRtn);
console.log('sendPage OUT: '+rtn);
rFile('404.htm', getRtn);
console.log('sendPage OUT: '+rtn);
}
function requestHandler(req, res) { // 1.
sendPage();
res.end();
console.log('sendPage OUT: '+rtn);
}
http.createServer(requestHandler).listen(3000);
I have the results from fs.readfile in getRtn(), but I cannot devise a callback scheme to get that same result into sendPage(), and possibly back to requestHandler().
sendPage() is going to do quite a few things, but it will be a collection point for a bunch of different things.
I've tried probably 25 times to insert a callback into getRtn(), but it errors with "unexpected function", and even if there was no error, I would't know... I just don't know. Even in the one callback that works inside fs.read, I don't know who is calling who.
But in the end, sendpage will gather all the results from a dozen different functions, some called from probably several functions deep, so the results will traverse many callbacks through many functions.
If anyone can show my how to continue calling back from the results I see in getRtn, all the way back to requestHandler() (or at least back to sendPage(), I'd be forever grateful.