Let's make comprehension easy ...
In Node, things are only visible to other things in the same file. By things, I mean variables, functions, classes and class members. So, given a file misc.js with the following contents:
Another file cannot access the x variable or addX function. This has nothing to do with the use of the var keyword. Rather, the fundamental Node building block is called a module which maps directly to a file. So we could say that the above file corresponds to a module named file1 and everything within that module (or any module) is private.
Now, before we look at how to expose things out of a module, let's look at loading a module. This is where require comes in. require is used to load a module, which is why its return value is typically assigned to a variable:
Of course, as long as our module doesn't expose anything, the above isn't very useful. To expose things we use module.exports and export everything we want:
Now we can use our loaded module:
There's another way to expose things in a module:
The difference is subtle but important. See it? We are exporting user directly, without any indirection. The difference between:
is all about how it's used:
It's pretty much a matter of whether your module is a container of exported values or not. You can actually mix the two within the same module, but I think that leads to a pretty ugly API.
Finally, the last thing to consider is what happens when you directly export a function:
When you require the above file, the returned value is the actual function. This means that you can do:
Which is really just a condensed version of: