Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't export function expression: "TypeError: xxx is not a function"

Tags:

node.js

module

I was trying to follow basic guide on modules. I've created test_module.js

var textFunction = function() {
    console.log("text");
};

exports = textFunction;

And then I tried to use it in my app.js:

var textFunction = ('./test_module');

textFunction();

But I get an error:

 TypeError: textFunction is not a function

Am I doing something wrong? Or it was a very old guide?

PS: exports works only if I declare it like this:

exports.text = function() {
    console.log("text");
}
like image 377
E1dar Avatar asked Dec 11 '25 22:12

E1dar


1 Answers

exports is a local variable. Assigning to it won't change the exported value. You want to assign to module.exports directly:

module.exports = textFunction;

module.exports and exports initially refer to the same value (an object), but assigning to exports won't change module.exports, which is what counts. exports exists for convenience.


The other issue is that you are not properly requiring the module, but that may just be a typo. You should be doing

var textFunction = require('./test_module');

var textFunction = ('./test_module'); just assigns the string './test_module' to textFunction and we all know that strings are not functions.

like image 142
Felix Kling Avatar answered Dec 13 '25 17:12

Felix Kling