Saturday 22 December 2018

JavaScript: Explain about module.exports

Whenever you load a module using require() function, it returns module.exports object of that module.

Let me explain with an example.

models.js
function Employee(firstName, lastName, addr){
	this.firstName = firstName;
	this.lastName = lastName;
	this.addr = addr;
	
	this.printInfo = function(){
		console.log("firstName : " + this.firstName);
		console.log("lastName : " + this.lastName);
		this.addr.printInfo();
	}
}

function Address(city, country){
	this.city = city;
	this.country = country;
	
	this.printInfo = function(){
		console.log("city : " + this.city);
		console.log("country : " + this.country);
	}
}

module.exports.Employee = Employee;
module.exports.Address = Address;

As you see models.js, I exported Employee and Address functions. So whoever loading the module models.js using require function, those can acceess Employee and Address constructor functions.

module.exports.Employee = Employee;
module.exports.Address = Address;

app.js
var models = require("./models.js");

var Employee = models.Employee;
var Address = models.Address;


var addr = new Address("Bangalore", "India");
var emp = new Employee("Krishna", "Gurram", addr);

emp.printInfo();

$node app.js
firstName : Krishna
lastName : Gurram
city : Bangalore
country : India

You can even export the functions, types or anything in the module using object literal notation like below.

module.exports = {
         Employee : Employee,
         Address : Address
}

Example 2

Emp.js

function Employee(firstName, lastName){
	this.firstName = firstName;
	this.lastName = lastName;
	
	this.printInfo = function(){
		console.log("firstName : " + this.firstName);
		console.log("lastName : " + this.lastName);
	}
}

module.exports = Employee;

App.js

const Employee = require("./Emp.js");

var emp = new Employee('Krishna', 'Gurram');

emp.printInfo();

Output
firstName : Krishna
lastName : Gurram

While loading the module using require function, you no need to specify .js file extension.

const Employee = require("./Emp");




Previous                                                 Next                                                 Home

No comments:

Post a Comment