Node Module System
Every file in a Node application is considered a module.
Values defined are scoped in their file. If you want to use a value, you must explicitly export it from its file and import it into another file.
This idea is the same as in ES6 modules. The only difference is the syntax of exports and imports.
Nodes default module system is based on CommonJS.1
// acount.js file
const INTEREST_RATE = 0.2;
class Account {
constructor(balance) {
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
}
widthraw(amount) {
this.balance -= amount;
}
}
module.exports.interest = INTEREST_RATE;
module.exports.Account = Account;
Notice the use of module.exports
instead of the export
keyword in ES6 modules.
The
module.exports
is a JavaScript object. Any value you want to export can be added as a property to theexports
object.
We use the require
function (instead of ES6 import
) to access variables exported from other modules.
// index.js file
const { Account } = require("./account.js");
const checking = new Account(100);
checking.deposit(20);
console.log(checking.balance);
- The
require
function takes the module's location relative to the current file. - It returns the
module.exports
object from the module file. I have used Destructuring assignment to destruct theexports
object. - The require statement can be placed anywhere in a file, but it is typically put at the top. (Consider this a good practice and follow it!)
You can also use the ES6 module system with Node. Please refer to Node's document on ECMAScript 2015 (ES6) and beyond.