Create Modules
Create new Javascript files as below:
Create Module 1
Create new Javascript file named demo1.js. This file contains code demo as below:
var age = 123;
var fullName = 'ABC';
let price = 4.5;
module.exports = { age, fullName, price };
Create Module 2
Create new Javascript file named demo2.js. This file contains code demo as below:
function generateRandom() {
return Math.random();
}
function sum(a, b) {
return a + b;
}
module.exports = { generateRandom, sum }
Create Module 3
Create new Javascript file named demo3.js. This file contains code demo as below:
class Product {
constructor(id, name, price, quantity) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
}
toString() {
return 'Id: ' + this.id + '\nName: ' + this.name + '\nPrice: ' + this.price + '\nQuantity: ' + this.quantity;
}
total() {
return this.price * this.quantity;
}
}
module.exports = { Product }
Create Index File
Create new Javascript file named index.js. This file contains code demo as below:
let module1 = require('./module1.js');
let module2 = require('./module2.js');
let module3 = require('./module3.js');
console.log('Age: ' + module1.age);
console.log('Full Name: ' + module1.fullName);
console.log('Price: ' + module1.price);
console.log('Generate Random: ' + module2.generateRandom());
console.log('Sum: ' + module2.sum(1, 2));
let product = new module3.Product('p01', 'name 1', 5, 2);
console.log(product.toString());
console.log('Total: ' + product.total());
Output
Use node index.js statement run code demo
Age: 123
Full Name: ABC
Price: 4.5
Generate Random: 0.8066028429716401
Sum: 3
Id: p01
Name: name 1
Price: 5
Quantity: 2
Total: 10