简体   繁体   中英

node.js module/export system: is it possible to export a module as a function

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?

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.

Do:

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

and it works the way you want.

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM