Like most programming languages, Node.js uses modules as a way of organizing code. The module system allows you to organize your code, hide information, and only expose the public interface of a component using module.exports.
Node.js uses the CommonJS specification for its module system:
- Each file is its own module, for instance, in the following example, index.js and math.js are both modules
- Each file has access to the current module definition using the module variable
- The export of the current module is determined by the module.exports variable
- To import a module, use the globally available require function
Let's look at a simple example:
// math.js file
function add(a, b)
{
return a + b;
}
…
…
module.exports =
{
add,
mul,
div,
};
// index.js file
const math = require('./math');
console.log(math.add(30, 20)); // 50
To call other functions such as mul and div, we'll use object destructuring as an alternative when requiring the module, for example, const { add } = require('./math');.
The code files for the section The Module System are placed at Code/Lesson-1/b-module-system.
The code files for the section The Module System are placed at Code/Lesson-1/b-module-system.