Introducción

[~/javascript/node.js/creating_modules(master)]$ cat foo.js 
var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is '
           + circle.area(4));

[~/javascript/node.js/creating_modules(master)]$ cat circle.js 
var PI = Math.PI;

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

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

[~/javascript/node.js/creating_modules(master)]$ node foo.js The area of a circle of radius 4 is 50.26548245743669

El módulo circle.js exporta las funciones area() y circumference(). Para exportar un objeto lo añadimos al objeto expecial exports.

Las variables locales al módulo serán privadas. En este ejemplo la variable PI es privada a circle.js.

[~/javascript/node.js/creating_modules(master)]$ node debug foo.js 
< debugger listening on port 5858
connecting... ok
break in foo.js:1
  1 var circle = require('./circle.js');
  2 console.log( 'The area of a circle of radius 4 is '
  3            + circle.area(4));
debug> n
break in foo.js:2
  1 var circle = require('./circle.js');
  2 console.log( 'The area of a circle of radius 4 is '
  3            + circle.area(4));
  4 
debug> repl
Press Ctrl + C to leave debug repl
> circle
{ circumference: [Function],
  area: [Function] }
> circle.area(2)
12.566370614359172
> PI
ReferenceError: PI is not defined
>



Casiano Rodriguez León 2015-01-07