Find your content:

Search form

Learn nodejs simple way - What is module in nodejs?


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");

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.


module.exports = function(d){

your program

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


How to export the data using module?

// data.js
module.exports = {

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?


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");

My Block Status

My Block Content