Asynchronous File IO

In notebook:
FrontEndMasters Real-Time Web with Node.js
Created at:
2015-10-13
Updated:
2015-10-13
Tags:
JavaScript Fundamentals Node JS backend
Video Course on Real-Time HTML5 with Node.jsthe module pattern

According to Kyle the file organisation with commonjs lends itself more to the module pattern than the delegation or prototypal pattern.
 
mynote: not necessarily, see CommonJS Modules Kevin Whinnery class

Kyle does 90% or more with modules without prototypes, (and surely not classes)

async

most Node utilities have a sync and async form

​fs.readFileSync​ vs. ​fs.readFile​ 
the async versions accept a callback - you cannot use the just ​return​ 

so you need to provide a callback for the ​say​ function

instead of this:
  function say(filename) {
    return fs.readFileSync(filename);
}
the async version

need to pay attention to the error-first callback style
  function say(filename, cb) {
    return fs.readFile(filename, cb);
}
// then use it like this
//  error-first
say(args.file, function(err, contents){
    console.log(contents)
});
need to handle the error:
  say(args.file, function(err, contents){
    if(err){
        console.error("Error", err);
    }
    else {
        console.log(contents)
    }
});
Kyle simulates a database call to demonstrate the callback and asynchronisity 
  function say(filename, cb) {
    return fs.readFile(filename, function(err, contents){
        if(err){
            cd(err); // erro first
        }
        else {
            setTimeout(function(){ // just to simulate a database call
                cb(null, contents);
            }, 1000);
        }
    });
}