顯示具有 nodejs 標籤的文章。 顯示所有文章
顯示具有 nodejs 標籤的文章。 顯示所有文章

2021年11月8日 星期一

Cannot install npm modules "cross-env"

Problems

Installing npm module "cross-env" states the following error

npm error on every command: EEXIST: file already exists, mkdir 'c:\users\user\appdata\Roaming\npm'

Troubleshoot

  1. Try re-installing the module -> no luck
  2. Try installing with "npm install --force --save-dev cross-env" -> no luck
  3. Try removing npm cache -> no luck
Solutions
Turns out I have put the npm start scripts before actually install the module, which is the cause of the error, DO NOT update the script with the command "cross-env" before installing it.

References

2018年8月17日 星期五

[NodeJS] Import Module Without Executing the Script

When working on my nodeJS project, I encounter some kind of difficulties on the following scenario

I wrote an expressJS application, which in turn being allocated to be unit tested, the problem is I want to pass the expressJS application to my test program, so I figure out I can export the "app" from the "index.js", so I add

export default app


in my index.js, so finally I can export the app variable and import it to my unit test. But the problem is when I import the module, I also execute the code associated with module which is not what I want, is there anything like Python's if __name__ == "__main__"?

I just want to import the module without executing it, so I end up with the following strategies

I wrap all the actions in a function and return my app at the end

export function initApp() {
   app.use...
   app.use...
   return app;
}

Then I add this important snippet

if (require.main === module) {
    initApp();
}

This is important ! It tells nodeJS only if this file being run by node can the initApp being executed, so in my unit test case, I could just safely import this module without unintentionally execute the initApp function