Find your content:

Search form

Learn nodejs simple way - What is module in nodejs?

 
Share

When you write Node.js applications, you could actually put all your code into single index.js file, no matter how large or complex your application is. The Node.js doesn’t care. But in terms of code organization, you would end up with a hard to understand and hard to debug mess quite quickly. So as a human being, you should care about how to structure your code. This is where modules come in.

How to create a module in Nodejs?

You can easily create a module and include them in your program. Create a file called "datetime.js" and add the following code.

module.exports.currenttime = function(){
    return new Date().getTime()
}

include the above created module in your program(moduleexample.js) and call the currenttime method.

var dt = require("./datetime.js");
console.log(dt.currenttime);

When you run "node moduleexample.js" you get the current time. In the above example we have given currenttime as function name. We could export the anonymous function too. Check out the below code.

//log.js

module.exports = function(d){
  console.log(d);
}

your program

var log = require("./log.js");
log("Sample data");

 

How to export the data using module?

// data.js
module.exports = {
   firstname:"John",
   lastname:"Bartel"
}

in your program, use the data.js file to access the defined data.

var dat = require("./data.js");
console.log(dat.firstname+" "+data.lastname);

 

How to export function as a class?

//person.js

module.exports = function Person(first, last){
  this.first = first;
  this.last = last;
  this.fullName = function(){
    return this.first + " " + this.last;
  }
}

 

defining function with this keyword which act as a class where you can create object for the above implementation. Check out below code.

var Person = require("./person.js");
var p = new Person("John", "Bartel");
console.log(p.fullName()); 

My Block Status

My Block Content