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);

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.



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:

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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.