File Streams

In notebook:
FrontEndMasters Real-Time Web with Node.js
Created at:
2015-10-13
Updated:
2015-10-13
Tags:
JavaScript Node JS backend
Video Course on Real-Time HTML5 with Node.js​fs.readFile​ reads in one chunk 

better to read it in a file stream

streams use buffers - memory efficient
​req​ and ​res​ are also streams (in the httpServer)
request stream 

reading a big file with streams: 
  function readFile(filename){
    return ASQ(function(done){
        var contents = "";
        var stream = fs.createReadStream(filename); // add this point it doesn't start reading the file
        // we have to listen to events
        stream.on("data", function(chunk){
            contents += chunk;
        });
        // there's an event when it's finished
        stream.on("end", function(){
            done(contents);
        });
    });
}