Search code examples
javascriptnode.jsexportrequire

Node Minor Code Issues - Require and Exported Functions


In a Previous Commit:

  • We Call A Function like So var previousRoute = appRouter.getPreviousRoute();
  • Where appRouter is var appRouter = require("app_utilities/default/app-router");
  • and app-router contains an export as the following:
module.exports = {
   getPreviousRoute: getPreviousRoute
}

function getPreviousRoute() {
   return window.appPreviousRoute;
};

however in a latter commit the following line errors:

var previousRoute = appRouter.getPreviousRoute();

The Error would be: Uncaught TypeError: appRouter.getPreviousRoute is not a function

and we have to change it to: var previousRoute = appRouter.getPreviousRoute;

I would like to know what would make it that we would need to drop the parentheses?

I have ran:

  • node -p process.versions.v8
    • 6.8.275.32-node.36

Solution

  • Most likely as you have declared a variable not the type function to export and the variable inside export holds the reference of the function so if you directly access getPreviousRoute a function it will produce an error as you did not export a function and the program will not find that. So in terms of working when a variable is called the program will find that its declared then will look for its reference function that you gave and will execute it

    Instead if you will export like

    exports.getPreviousRoute = ()=>{}
    

    It will not show you an error as its a type of function and will be accessible let me also point if i am wrong