Skip to main content

Loading- Exporting Modules in Node.Js

Loading a module:

In node you can load module either using the path to the module or giving name  of the module. require keyword is used to load  module in node. Its look for the file in given path to load module if the require module is not core node module. You can install third party module using NPM(Node Package Manger). It downloads from the global repository to your local machine.

var module = require('module-name');

The require function returns an object that represent the module which have exported. It can be any javascript data type. It could be function, an array, any javascript object.

Exporting a module:

The CommonJs Module system is use to share the object or properties in node.js. Since Javaascript runs program in global scope. CommonJs Module is one of the best way for creating and sharing namespace in the javascript environment.

Here below given an example to export a function in node.js.

//person.js
/**
* Created by deepak.m.shrma@gmail.com on 11/1/15.
*/
function Person(name, age, desc) {
  var _name = name || 'no_name',
      _age = age || 1 || 'just_born',
      _desc = desc || 'i am just a moron';
  function getInformation() {
      return {
          name: _name,
          age: _age,
          desc: _desc
      }
  }
  return {
      get: getInformation
  }
}
module.exports = Person;

Here module is representing current module you are in. module.exports is object that module will export. In above example, It is representing a constructor of the Person function. You can export multiple properties by module.exports.
For example, You can export multiple function and attributes:
//multiple-properties.js
/**
* Created by deepak.m.shrma@gmail.com on 11/1/15.
*/
function fun1() {
  console.log('this is func 1');
}
function fun2() {
  console.log('this is func 2');
}
function fun3() {
  console.log('this is func 3');
}
module.exports.fun1 = fun1;
module.exports.fun2 = fun2;
module.exports.fun3 = fun3;
module.exports.val = 'some_value';

//implementation.js
var myModule2 = require('./multiple-properties');
myModule2.fun1(); // -> this is func 1
myModule2.fun2(); // -> this is func 2
console.log(myModule2.val); // -> some_value

Loading a module:

As above mention, we can load module using require function. require function resolve the path and load the relevant module for you which you can assign to any local variable. There are several way to load a module.

Loading a core module:

Node has several modules with its binary distribution. You can load those module by its name. You dont have to specify the path for it.

For example, If you want to load node’s core http module. You can do that by
      var http = require('http');
It will load the node’s http module by which you can create server and play with it.
Note: Node will load preferentially core module instead of any third-party module having same name.

Loading a file module:

You can load a non-core module providing the absolute path to that module.
For Example,

var myModule = require('/home/deepak/my_modules/my_module');
You can also provide the relative path to the file.

var myModule = require('../my_modules/my_module');
var myModule2 = require('./lib/my_module_2');

You can skip the .js extension. It looks for the same file. If it does not find file with same name it look for the file with .js extension.

Loading a folder module:

You can also load the module as package by providing its absolute path to the directory.

var sample = require('./sample-module');
if (sample)
  console.log('sample module has been loaded.. :-)');

By default node look for the package definition of the module which is package.json. if it won’t find the package.json. It looks for the ./sample-module/index.js.
You can define your package/module settings in package.json. Inside the package.json it check for the main attribute which represent the entry point of the module.
For example:
{
"name": "sample-module",
"version": "0.0.1",
"main": "./lib/sample-module.js"
}

Here name is name of the module and main as mention, entrypoint of the module. For more information please refer to creating-node-modules.

Loading module from node_modules files:

As you can install modules either locally or globally to your local system using NPM. When you install a module using npm, npm install it to ./node_modules folder either current location or on global npm repository according to param that you have pass while installation. For more information refer.

When you require a module using its name and if its not the code node module. It looks for that module inside the node_modules folder in current directory. If it won’t find the module it goes back to parent directory. If module is not there it keep descending to parent folder. until it don’t reach to the root folder.
For example:
var myModule = require('sample-module.js');
This statement will looks for the module ./node_modules/sample-module. If module not there it will looks for ../node_modules/sample-module and so on.

Caching of the modules:

Everytime you call require(‘some-module’). Its returns same module that node has resolve with same file name.
For example, You have create a module with some message.
/**
* Created by deepak.m.shrma@gmail.com on 11/1/15.
*/
console.log('module my_module initializing...');
function sayHi() {
  console.log('saying hi from module..');
}
module.exports.sayHi = sayHi;
console.log('my_module initialized.');
Once you require the module by
var sample = require('./sample-module');
You will get logs on console like.
module sample-module initializing...
sample-module initialized.
What if you call require two times
var sample = require('./sample-module');
var sample2 = require('/home/intelligrape/projects/angularjs-tabs-and-lazy-data-loading/beginning-with-nodejs/loading-exporting-modules/sample-module');

Output won’t be change even if you require module two times or more. Output would be same. This mean module runs and initialize for once.

Tips:

exports vs module.exports in node.js.

While coding you have seen exports instead of module.exports. exports is nothing but helper which is use to attach property of the module. It’s same as module.exports. If there is module.exports define in the definition of the module. Node ignore the exports.
Here the buggy-module:
/**
* Created by deepak.m.shrma@gmail.com on 11/1/15.
*/
console.log('module buggy-module initializing...');
module.exports = {
  sayHi: function () {
      console.log('i am stupid');
  }
}
exports.sayHi = function () {
  console.log('hi');
}
console.log('buggy-module initialized.');

When you run it to another file. Output would be.
var buggyModule = require('./buggy-module.js')
buggyModule.sayHi();

Logs:

module buggy-module initializing...
buggy-module initialized.
i am stupid

Conclusion:
Hope you have got lots of thing for leaning. For sample program please go to my github repo and download the source.

Comments

Post a Comment

Popular posts from this blog

Introduction to Node.js - Part-1 Node Command line Interface(CLI) App

Aim This document is get to start with the Node.Js. This is a simple introduction to Node and Its corresponding frameworks. This will help you to create a simple chit chat server application using node.js, express.js and socket.io. I have used the chat demo app of socket.io to learn you node. Introduction to Node.Js CLI Introduction to Node If you are from the Java and .net background. You might have create several JSP and ASP application to learn Java and ASP web framework. While create web app. You also learned JavaScript to interact with the HTML dom elements. If you go to the wikipedia definition of node which is “ Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux, FreeBSD, and IBM_i ”. It tells that Node is a framework where you can write code in Javascript programming language on s

Provide SSL support over your http NodeJs-Express API

A simple HTTPS server using node.js: Using ExpressJS and openssl, you can easily provide SSL support to your Api. For that you have to follow below given steps. Steps to create a https server. Generate an SSL certificate with that key Create a app.js file Install express module Run to Test your app. :-) Generate an SSL certificate with that key: For development purposes you can create a self-certified certificate. First, generate a private key on linux-based system. It will store a 1024 bit RSA key in the file key.pem openssl genrsa 1024 > key.pem Then, generate an SSL certificate with that key: openssl req -x509 -new -key key.pem > key-cert.pem Create a app.js file var fs = require("fs"),                 //Requires fs module to read key, cert files     express = require('express'),       // call express     app = express(),                     // define our app using express     http = require("http"),