Mar 23, 2016

Ways to export modules in nodejs

there are several ways to export modules in nodejs

  1. Simplest export
  2. Define a global
  3. Export by anonymous function
  4. Export by named function
  5. Export by anonymous object
  6. Export by named object
  7. Export by anonymous prototype
  8. Export by named prototype
  9. Export by Json

1. Simplest export

//hello.js
console.log('Hello World');

// app.js
require('hello.js');


2. Define a global : please don't pollute global space

// foo.js
foo = function () {
   console.log('foo!');
}

// app.js
require('./foo.js');
foo();

3. Export by anonymous function

// baz.js
module.exports = function () {
   console.log('baz!');
}

// app.js
var baz = require('./baz.js');
baz();

4. Export by a named function

// bar.js
exports.bar = function () {
    console.log('bar!');
}

// app.js
var bar = require('./bar.js').bar;
bar();

5. Export by anonymous object

// foo.js
var Foo = function () {};

Foo.prototype.log = function () {
   console.log('Foo!');
};

module.exports = new Foo();

// app.js
var foo = require('./foo.js');
foo.log();

6. Export by named object

// barr.js
var Barr = function () {};

Barr.prototype.log = function () {
   console.log('Barr!');
};

exports.Barr = new Barr();

// app.js
var barr = require('./barr.js').Barr;
barr.log();

7. Export by anonymous prototype

// foo.js
var Foo = function () {};

Foo.prototype.log = function () {
    console.log('Foo!');
}

module.exports = Foo;

// app.js
var Foo = require('./foo.js');
var foo = new Foo();
foo.log();

8. Export named prototype

// baz.js
var Baz = function () {};

Baz.prototype.log = function () {
    console.log('Baz!');
};

exports.Baz = Baz;

// app.js
var Baz = require('./baz.js').Baz;
var baz = new Baz();
baz.log();

9. Export Json

//foo.js
module.exports = {
    baz : function(){
        console.log('baz');
    },
    bar : function(){
        console.log('bar');
    }
}

//qux.js
var foo = require('./foo.js');
foo.baz();
foo.bar();

No comments :

Post a Comment