Search This Blog

2015-10-16

Node JS Modules

What is Module in Node JS

Modules make it possible to include other Javascript files into your applications. In fact, a vast majority of Node’s core functionality is implemented using modules written in JavaScript.

Using modules is simple: you use the require() function, which takes one argument: the name of a core library or a file system path to the module you want to load.

To make a module yourself, you need to specify what objects you want to export. The exports object is available in the top level scope in Node for this purpose.

Example, create hello.js and write the following code
 
exports.firstname='Manab';
exports.myfunction = function()
{  
return 'Hello World';
 
};
 
Then, in your index.js(calling Page),execute the module as below,
 
var hello = require('./hello.js');
console.log(hello.myfunction ()); // Print "Hello World"

 
But we also have the option of using the 'module.exports' to export just one single entity from our modules.

 

in hello.js

module.exports = function(){

//return Math.random();

return 'Hello World';
} 

 
In index.js
console.log(hello); // Print "Hello World"
 

Core modules :


Core modules that are provided by Node itself, examples are
 
1)var os = require ('os');
console.log(os);
console.log(os.platform());

2)var http = require('http');
console.log(http);

NPM Package Management  :

1)run 'npm init'.
2)Enter name, Version, Description and author and leave blank for other option to be defaulted.
3)It will generate package.json.
4)Manually create index.js as a default entry point
5)run 'npm install express --save'

The dependencies(in package.json) code block is as follows:
"dependencies": {
"express": "^4.9.6"
}



==>install 'express' which is getter than 4.9.6

6)run 'npm update' ==> after changing version of dependencies from package.json
7)run 'npm prune'  ==> after removing dependencies from package.json

 

NPM Modules :

This is the community modules find in the below location
https://www.npmjs.com/

Install the NMP modules after npm init and get a folder structure:

1)npm install underscore --save

var _ = require('underscore');
var names = ["Steve", "Stuart", "Ari", "Ayan"];
_.each(name, function(name){
console.log("Name is: " + name);
});


2)npm install    => if package.json(will get after npm init) contains the dependencies
 

Create Module(./)

Create fruit.js as below :

module.exports = function(name, description){
var name = name;
var description = description;
var functions = {
setName: function(nameIn)
{
this.description = description;
},
getInfo: function()
{
return{
name: name;
description: description;
}
}
};
return functions;
}



In Index.js

var fruit = require('./fruit.js');

var banana = fruit('banana', 'yellow fruit');
var cherry = fruit('cherry', 'small red fruit');
console.log(banana.getInfo());
console.log(cherry.getInfo());


 
 

No comments: