Multiple modules in Node.js

I'm one of the organizers for NodeSchoolDC
and at our meetups I see people get stuck on the exact same problem all the
time. That problem is exercise 6, Make it Modular, which is the first time
that you have to write a program that is split across two different files. I
wanted to go ahead and explain it here to clear things up.

What does require do?

The simple version is that require is a global function set up in Node that
finds another file on the system and executes it. It then gives you back
whatever is the value of that file's module.exports.

Scope inside a module

For now, you don't need to know any details about javascript closures, you just
need to know that when you require a file and get back its module.exports,
it has access to any variables defined in that file.

In Node, callbacks are always written to take an error as the first parameter.
This makes it easy to handle errors inside your calling code, which makes for
more maintainable programs. The above code in a more conventional style would
look like this:

Multiple callbacks

The other thing that makes this exercise tricky is that you are actually dealing
with two levels of callbacks.

Your main.js file needs to define a callback which your my-module.js will
call after it finishes. This callback will be the last thing called, so you
need to say what to do with an error if it exists and also what to do with the
list of filtered files.

Your my-module will also need to define a callback for fs.readdir to call
after that finishes. Inside that callback, you will need to "bubble" any errors.
That means that if an error exists, you can call the callback you've received
from main.js with that error. Otherwise, you can filter the files you've
received and then pass null (no error) and the filtered files to the callback
from main.js.

To reiterate, the key thing here is that the callback passed to my-module
needs to get called inside the callback given to fs.readdir.

Conclusion

The concept of splitting code across different modules can be pretty daunting at
first, but it's an incredibly useful tool for organizing your code. It helps to
know that there's nothing complicated going on, just simple javascript
functions. In fact, the patterns you just learned are the same ones used in all
Node modules you may find in the wild, and even in the Node core itself!

I would recommend you work through this exercise on your own (you're smart, you
can do it!), but afterwards if you're interested in seeing my solution, it's
posted here.