Node.js is an event-driven, server-side JavaScript
environment. Node runs JavaScript using the V8 engine developed by Google for
use in their Chrome web browser. The major speed increase is due to
the fact that V8 compiles JavaScript into native machine code, instead of
interpreting it or executing it as bytecode. http://blog.modulus.io/top-10-reasons-to-use-node
Node.js way: synchronous.
To perform a filesystem operation you are going to need the
fs module from the Node core library. To load this kind of module, or any other
"global" module, use the following incantation:
var fs = require('fs')
Now you have the full fs module available in a variable
named fs. All synchronous (or blocking) filesystem methods in the fs module end
with 'Sync'. To read a file, you'll need to use
fs.readFileSync('/path/to/file'). This method will return a Buffer object
containing the complete contents of the file.
Node.js way: asynchronous.
Instead of fs.readFileSync() you will want to use
fs.readFile() and instead of using the return value of this method you need to
collect the value from a callback function that you pass in as the second
argument.
Remember that idiomatic Node.js callbacks normally have the
signature:
function callback (err, data) { /* ... */ }
Also keep in mind that it is idiomatic to check for errors
and do early-returns within callback functions.
Node.js module
Create a new module by creating a new file that just
contains your directory reading and filtering function. To define a single
function export,
you assign your function to the module.exports object,
overwriting what is already there:
module.exports = {
foo: function ()
{
console.log("foo is here.");
},
bar: function ()
{
console.log("bar is here.");
}
};
To use your new module in your original program file, use
the require() call in the same way that you require('fs') to load the fs
module. The only difference is that for local modules must be prefixed with
'./'. The '.js' is optional here and you will often see it omitted. So, if your
file is named mymodule.js then
var mymodule =
require('./mymodule.js')