How to build a Node.JS package


Some time I was asked how to build a package in Javascript that can later be used in one or more projects with Node.JS as a standard framework packages or that are installed via NPM.


Well, it's very simple. First we must know the Javascript' affirmative "exports", it serves to provide variables, functions or objects from a Javascript script to another, example:

// File circle.js
var PI = Math.PI;

exports.name = "circle.js";

exports.area = function (radius) {
     return PI * radius * radius;
};

exports.circumference = function (radius) {
     return 2 * PI * radius;
};

Thus, our package "circle.js", can now be imported into any project we need it, using the statement "require", example:

// File test.js
var circle = require('./circle.js');

console.log('Package name: ' + circle.name);
console.log('Area of a circle with radius 4: ' + circle.area(4));
console.log('Circumference of a circle with radius 4: ' + circle.circumference(4));

Very well, as mentioned before, with the statement "exports" can provide variables, functions or objects from one script to another. Let us build a more advanced example, with an Object Map ("Object Map, A more appropriate name to refer to objects in JavaScript"), example:

// File elements.js
var circle = require('./circle.js');

// Element Box
exports.Box = function(width, length, height){
    this.width = width || 0;;
    this.length = length || 0;
    this.height = height || 0;
    this.getArea = function(){
        return ((this.width * this.length) * 2) + ((this.width * this.height) * 2) + ((this.length * this.height) * 2);
    }
}

// Element Cone
exports.Cone = function(radius, height){
    this.radius = radius || 0;;
    this.height = height || 0;
    this.getArea = function(){
        var generatrix = Math.pow(Math.pow(radius, 2) + Math.pow(height, 2), 0.5);
        return circle.area(this.radius) + (Math.PI * this.radius * generatrix);
    }
}

Changing the file "test.js" to:

// File test.js
var circle = require('./circle.js');
var elements = require('./elements.js');

function show(){
    this.write = function(message){
        console.log(message);
    }
}

exb = new show();

box =  new elements.Box(2, 2, 2);
cone =  new elements.Cone(3, 5);

exb.write('Package name: ' + circle.name);
exb.write('Area of a circle with radius 4: ' + circle.area(4));
exb.write('Box area: ' + box.getArea());
exb.write('Cone area: ' + cone.getArea());

Note that now we are importing objects too, so this way you can build your packages and reuse them in your code, and if you find it really useful, check the official website of the NPM create your profile and share your package with the community .
How to build a Node.JS package How to build a Node.JS package Reviewed by AJ Alves on quarta-feira, outubro 03, 2012 Rating: 5

Nenhum comentário:

Tecnologia do Blogger.