Modules Part 2 - Writing modules
Modules are used to organize and create structure in program code. You know how to load modules using require. Now you're wondering "How am I supposed to write them?". Let's see how modules work from the module writers perspective so you can use them to divide your application into logical components.
Write modules by assigning to
Writing modules in Node.js is straightforward. Create a .js file and write your program logic and assign to
module.exports what you want to pass to the consumer of that module. There are no restrictions on what you can pass - both functions and variables are allright.
object is initially created as an empty object literal. Fill it with objects that you want to pass to the caller of
require(). As a shorthand, the same object is also available in
You can use
exportsshorthand. The following are equivalent, using
require() is replaced by
In the calling end the
require() call gets replaced with
module.exports of the loaded module.
Here the call to
require('./log')can be thought as if it was replaced by contents of the
and running main would output:
Module has local variables and functions
The module source can be thought as if it would be wrapped inside a function. All variables and functions are local to the source file and only what is assigned to
module.exports will be passed to the caller.
For example in a more complex module
markUserRegistered() will not be visible to the caller of
Returning a function
Instead of assigning properties to empty
module.exports object literal you can also replace it completely with a function. This can be used for returning initialization functions or constructors to be called using
new. It is important to note that assigning function simply to
exports will not bring the desired result,
module.exports must be explicitly used.
is directly replaced with
module.exports of the loaded module. This allows a pattern where a function call is immediately performed on the returned module. This is commonly seen pattern in the
That's all there really is to writing modules. Write program logic in a separate file and assign to
module.exports what you want pass to the consumer of the module.
There are 350 000 NPM packages. Your task: pick one.
Learn what to look for in a reliable NPM package.