File IO & Modules
Video Course on Real-Time HTML5 with Node.jscommonjs modules
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 bymodule.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