简体   繁体   中英

NodeJS: module.exports property is not a function

I have the following in a module file:

module.exports = {
    myfunc: myfunc
};

var myfunc = function(callback){    
        callback(err,reply);    
};

In an other file I got the reference to that module

var mymodule = require('./modules/mymodule');
mymodule.myfunc(function(err, reply){ ... });

When I call the mymodule.myfunc() I get an error saying "property 'myfunc' is not a function". This happens only with exported functions. The same module exports some 'string' fields and these are working just fine.

When you assign module.exports , the myfunc function is still undefined. Try to assign it after declaring it:

var myfunc = function(callback){    
    callback(err,reply);    
};

module.exports = {
    myfunc: myfunc
};

To preserve your original ordering of module.exports at the top of your file, change your var myfunc initialization to a function myfunc declaration so that the latter is hoisted .

module.exports = {
    myfunc: myfunc
};

function myfunc(callback){    
    callback(err,reply);    
};

Declarations are hoisted , but initializations are not, which is why your original example did not work. w3schools has a practical description of JavaScript Hoisting .

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