Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function is triggered unexpectedly – nodeJS

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading