2

I get the error: "login is not defined" on my node.js app, when I try to get the function login in my server.js from a module module1.js which needs data:

//module1.js
module.exports = (data) => {
   var login = function(data){
      console.log(data)
   }
   exports.login = login;
};

//server.js
var test = require(__dirname + '/app/modules/module1.js')(data);
test.login();

1 Answer 1

2

When node starts executing module code, both module.exports and exports point to the same object. When you re-assign module.exports, you're specifying another object that will be returned from a module. In you case it's a function (data)=>{...}. The exports variable keeps pointing to the old module object.

You need the following:

module.exports = (data) => {
   var login = function(){
      console.log(data)
   }
   return {login: login};
};

Or this way shorter:

module.exports = (data) => {
   return {login: function(){
      console.log(data)
   }};
};

Or, if you want to export both functions, you need to add them to exports object.

Sign up to request clarification or add additional context in comments.

1 Comment

@PierreNicolas, you're welcome. Don't forget you can accept my answer it it helped)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.