Monday 8 October 2018

node.js: Exporting custom modules

In my previous post, I explained how to import external modules using require() function (require(): Loadrequired modules).

In this post, I am going to explain how to import custom modules using ‘require()’ function.

I defined file structure like below.
HelloWorld.js
customModules
         ->Employee.js

I would like to import Employee.js module in HelloWorld.js file, you can do that using require("./customModules/Employee").

Employee.js
var Employee = function(firstName, lastName){
 this.firstName = firstName;
 this.lastName = lastName;
}

module.exports = Employee;

HelloWorld.js
var Employee = require("./customModules/Employee");

var emp1 = new Employee('Krishna', 'Ponnam');

console.log(`Employee first name : ${emp1.firstName}`);
console.log(`Employee last name : ${emp1.lastName}`);

Output
Employee first name : Krishna
Employee last name : Ponnam


Previous                                                 Next                                                 Home

No comments:

Post a Comment