Home > Software engineering >  Function is triggered unexpectedly - nodeJS
Function is triggered unexpectedly - nodeJS

Time:07-08

I have two entry points in my project updated.ts & test.ts, In update.ts there is a self invoked function like this

let main = ()=>{// do something}
main()

but when I run in my terminal node test.ts main() is also triggered, Is this a compiler thing? how can I work around it? I do import other functions from update.ts expected behaviour: run node test.ts and import other functions from updated.ts without main() being triggered

CodePudding user response:

When you load a module, anything in the body of the module — including the defining of variables and evaluation of main() — will run.

It's necessary. Consider:

let initialized = null;

const main = () => {
    initialized = new Date();
} 

main();

export const other = () => {
    return initialized;
}

… you might only be importing other but its functionality depends on the side effects of the rest of the code in the module running.

If you don't want to call main() every time the module is loaded, then don't put main() in the body of that module.

You might want to split main and the other code in the module into separate modules.

  • Related