Tuesday 19 February 2019

Node.js : index.js file


In this post, let’s try to understand the importance of index.js file in node.js

When you pass a folder to the node.js require module, it first checks the package.json file to load the specific node.js file. If package.json file is not located, then node checks for index.js, and finally index.node

Let’s confirm this behavior using simple example.

Create new directory ‘indexDemo’.

Create a directory ‘myModels’ inside indexDemo directory.

Go to myModels and define package.json, models.js like below.

package.json
{ 
 "main" : "models.js" 
}

‘main’ attribute tell the main js file to be loaded, when user specifies the directory myModels in require function.


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,
 Address : Address
}

Now create a file index.js in indexDemo directory.


index.js
models = require("./myModels")

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

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

emp.printInfo();


No go to the parent directory of indexDemo directory and execute the command 'node indexDemo'. You can see below messages in console.

$>node indexDemo
firstName : Krishna
lastName : Gurram
city : Bangalore
country : India



Previous                                                 Next                                                 Home

No comments:

Post a Comment