What's the best way to fetch methods from Node.js?

We believe that I want to expose a method called Print

  • Binding method like 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 go into printNow()

by placing the code require('Printer.js').printNow()

in any external .js node file.

  • the export method itself with module.exports

    :

File saved as Printer2.js

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

      

Then go to printNow()

by placing the code require('Printer2.js').printNow()

in any external .js node file.

Can anyone tell me what is the difference and the best way to do this in regards to Node.js?

+3


source to share


2 answers


Definitely the first way. It's called substack pattern

, and you can read about it on Twitter and on the Mikeal Rogers blog . Some code examples can be found in 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();
  }
};

      

+4


source


In the first example, you create 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 topic: 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 (assuming you are using the new one as indicated), but only one instance of the second approach.

+3


source







All Articles