Reading Class 01 - meron-401n14/seattle-javascript-401n14 GitHub Wiki
Module#
Ø In the Node.js module system, each file is treated as a separate module.
example : consider a file named foo.js
const circle = require('./circle.js);
console.log(` The area of a circle of radius 4 is ${circle.ar
On the first line, foo.js loads the module circle.js that is in the same directory as foo.js
Here are the contents of circle.js:
Const { PI } = Math; exports.area = ( r) => PI * r **2; exports.circumference = ( r ) => 2 * PI * r;
The module circle.js has exported the functions area() and circumference(). Functions and objects are added to the root of a module by specifying additional properties on the special export object.
Variables local to the module will be private, because the module is wrapped in a function by Node.js. In this example the variable PI is private to the circle.js .
The module.exports property can be assigned a new value(such as a function or object ).
Example : below , bar.js makes use of the square module , which exports a Square class:
Const square = require( './square.js);
Const mySquare = new Square(2);
Console.log(`The are of mySquare is ${mySquare.area()}`);
The square module is defined in square.js:
// Assigning to exports will not modify module, must use module.exports
module.exports = class Square {
Constructor(width) {
this.width = width;
}
Area() {
Return this width ** 2;
}
};
The module system is implemented in the require('module) module.