0

I want to do something like this in Dispatch.js

function handle(msg) {
    ....
}
exports = handle;

and this in the calling index.js

var dispatch = require("./Dispatch);
dispatch("data");

Any ideas?

4 Answers 4

4

exports = handle

This creates a local variable called exports. This is different from overwriting module.exports.

module.exports = handle

This overwrites the exports variable that lives in module scope, this will then be read by require.

In the browser window["foo"] and foo are the same, however in node module["foo"] and foo behave subtly different.

The local variable scope context and module are not the same thing.

Sign up to request clarification or add additional context in comments.

Comments

1

Do:

function handle(msg) {
    ....
}
module.exports = handle;

and it works the way you want.

1 Comment

or module.exports = function(msg) { }
0

The problem behind this issue (exports vs module.exports vs exports.something) is best described in this article:

http://www.alistapart.com/articles/getoutbindingsituations

The first version (exports = handle) is exactly the problem: the missing binding that is mandatory in javascript:

exports = handle means window.exports = handle (or whatever node.js has as the global object)

Comments

0

Another way of seeing the problem is thinking about how node could load your module:

function loadModule(module, exports) {

inside here comes your module code

}

If your code overwrites the exports parameter (exports = handle), this change is not visible from the outside of this function. And for this overwriting one can use the module object.

The problem would not occur if exports would be a variable visible in the scope where the function body is.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.