Amol M Kulkarni
Amol M Kulkarni

Reputation: 21629

What is the best way to expose methods from Node.js?

Consider I want to expose a method called Print

  1. Binding method as prototype:

File Saved as Printer.js

var printerObj = function(isPrinted) {
            this.printed = isPrinted;        
    }

printerObj.prototype.printNow = function(printData) {
        console.log('= Print Started =');
};
module.exports = printerObj;

Then access printNow() by putting code require('Printer.js').printNow() in any external .js node program file.

  1. Export method itself using module.exports:

File Saved as Printer2.js

var printed = false;   
function printNow() {
console.log('= Print Started =');
}    
module.exports.printNow = printNow;

Then access printNow() by putting code require('Printer2.js').printNow() in any external .js node program file.

Can anyone tell what is the difference and best way of doing it with respect to Node.js?

Upvotes: 3

Views: 2248

Answers (2)

Hector Correa
Hector Correa

Reputation: 26690

In the first example you are creating a class, ideally you should use it with "new" in your caller program:

var PrinterObj = require('Printer.js').PrinterObj;
var printer = new PrinterObj();
printer.PrintNow();

This is a good read on the subject: http://www.2ality.com/2012/01/js-inheritance-by-example.html

In the second example you are returning a function.

The difference is that you can have multiple instances of the first example (provided you use new as indicated) but only one instance of the second approach.

Upvotes: 3

zemirco
zemirco

Reputation: 16395

Definitely the first way. It is called the substack pattern and you can read about it on Twitter and on Mikeal Rogers' blog. Some code examples can be found at the jade github repo in the parser:

var Parser = exports = module.exports = function Parser(str, filename, options){
  this.input = str;
  this.lexer = new Lexer(str, options);
  ...
};

Parser.prototype = {

  context: function(parser){
    if (parser) {
      this.contexts.push(parser);
    } else {
      return this.contexts.pop();
    }
  },

  advance: function(){
    return this.lexer.advance();
  }
};

Upvotes: 4

Related Questions