shai
shai

Reputation: 55

understanding module.exports with callback

I have a situation where I am creating a node module that returns only when an asynchronous operation is completed. One way to do this (shown below), is to assign module.exports a function with a callback parameter. Inside the function, you would then return the callback.

Here's an example of what I describe, with done being callback:

// module called test.js
module.exports = function(done) {
  // do something asynchronous here
  process.nextTick(function() {
    done();  //  call done when the asynchronous thing is complete...
  }
}

Where I am getting hung up, is in how the callback done is indeed being executed, considering I don't define it anywhere...

For example, in vanilla javascript, I can pass done as parameter and then call it within the function, as long as I create the callback function in the invocation.

function testAsyncCb(msg, done) {
  console.log(msg);
  setTimeout( function() {
    done();
  }, 1000);
  console.log("last line in code");
}

testAsyncCb("testing", function(){ console.log("done"); });  // invocation with callback function

Back in the first node example, somewhere the call to module.exports by require() is creating a function for the done() to resolve to right? If not, how is the callback resolving?

Having a hard time finding information for how this works. Any help/direction is appreciated.

Upvotes: 4

Views: 7755

Answers (1)

sagie
sagie

Reputation: 1777

Think of module.exports as an object (module.exports = {}). So whatever you put to the object will be publicly visible to anyone do require module.

For instance, you have

 module.exports = function myFunc() {} 

then require to that would mean

var abc = require('./my-module'); --> abc == myFunc

if you would do

module.export.myFunc = function () {}

than require would be

var abc = require('./my-module'); --> abc == {myFunc: function () {}}

require operation is sync, not async like in requirejs (meaning not AMD but more like commonjs).

see http://www.sitepoint.com/understanding-module-exports-exports-node-js/ for more info also for nodejs official docs: https://nodejs.org/api/modules.html

Upvotes: 6

Related Questions