How does “Exports” work in Node JS

1 בינואר 2014

no comments

If you wandered how does “NodeJS exports” works under the covers here in the answer.

The trick is simple: wrap your function (object definition) with a wrapper function that accepts the exports object from the global scope.

This makes exports global, allows you to attach your code to it and prevents your code from reaching the global scope.

Code Snippet
  1. //wrapper function
  2. (function (exports, require, module, __filename, __dirname) {
  3.     //your code
  4.     var calculator = function() {
  5.         return {
  6.             add: function(a, b) { return a + b; }
  7.         };
  8.     };
  9.     exports.add = calculator;
  10. });

Hope this helps

Manu

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*