File IO & Modules

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

Creating a module

create a module that can read a file and display its contents
commonjs modules
​everything you declare in your file is private. you need to explicitly export by

​module.exports.myfunc = myfunc​  
our public API is ​module.exports​  
we can replace this object or add to it 
  function say(filename) {
    return fs.readFileSync(filename);
}

var fs = require("fs");

module.exports.say = say;
in a command line tool blocking is not a big issue you can use synchronous file reading (​fs.readFileSync​)

buffers

the ​say​ function will return something like this: <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64 0a>

everything is done in array string (especially in streams)

you need to call ​toString()​ on your data