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.

Another scenario where i found this annoying issue was if explicitly imported only the function that my consumer needs

Say for example your exported modules looks like below

module.exports = {
    func1 : async function func1(){}
    func2 : async function func2(){
        await this.func1(); // causes error : func1 is not a function
    }
}

Now your consumer of above module looks like below:

const { func2 } = require('../theExportedModules'); 
//above only imports func2 but not its dependents and is not initialized    
await func2(); //func2 called

Now func2() gets called from your consumer but func2() will not be able to call the func1() because it finds that func1() is not a function. Code breaks!

Read More:   How to get object length [duplicate]

solution import entire modules:

const theExportedModules = require('../theExportedModules'); 

we could also just import func1 as well but then it would be an unused variable and we would get a warning for that.


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts