DEV Community

Sonu Jha
Sonu Jha

Posted on

Understanding Node Modules

Starting a Node application

  1. create a folder - node-examples
  2. now intiliaze the package.json by typing - npm init
  3. Accept the standard defaults suggested and the update the package.json
    file until you end up with the file containing the following
    {
    "name": "node-examples",
    "version": "1.0.0",
    "description": "Simple Node Examples",
    "main": "index.js",
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index"
    },
    "author": "Sonu Jha",
    "license": "ISC"
    }

  4. now create a file name index.js

var rect = {
perimeter : (x,y) =>(2*(x+y)),
area: (x,y) => (x*y)
};

function solveRect(l,b) {
console.log("Solving for rectangle with l = " + l + " and b = " + b);
if (l <= 0 || b <= 0) {
console.log("Rectangle dimensions should be greater than zero: l = "
+ l + ", and b = " + b);
}
else {
console.log("The area of the rectangle is " + rect.area(l,b));
console.log("The perimeter of the rectangle is " + rect.perimeter(l,b));
}
}
solveRect(2,4);
solveRect(3,5);
solveRect(0,5);
solveRect(-3,5);

  1. To run the Node Application type the following at prompt npm start

A simple Node Module

  1. Now create a file name rectangle.js and the following code to it:

exports.perimeter = (x, y) => (2*(x+y));

exports.area = (x, y) => (x*y);

  1. Then Update index.js as follows :

var rect = require('./rectangle');

In Conclusion, A Node Modules are js files that are imported using require() function to use the functionalty.

Top comments (0)