Using NVM for Node.js: Why are npm modules installed in a shared folder?

I’ve set up NVM to manage Node.js versions following certain guidelines. However, I’ve noticed that when I toggle between different Node.js versions and use npm to add modules, they all get stored in the same global ‘node_modules’ directory (~/node_modules/) instead of the corresponding version-specific ‘node_modules’ folder. Does anyone know how to fix this issue?

Hey Alex,

The issue you're facing is likely due to using npm with the global flag. To ensure modules are installed per Node.js version with NVM, avoid the -g flag unless you specifically want a global install. For version-specific installs, just use:

nvm use <version>
# then
npm install <package>

This will store modules in the local node_modules directory of the current version. If you want to check which version you are using with NVM, you can run:

nvm current

Hope that helps!

In addition to what has already been mentioned, NVM operates by managing different versions of Node.js, each kept in its own directory. If you're noticing that global npm modules are being installed in a shared directory, the underlying reason might be more related to the configuration of your npm or a permissions setup rather than NVM itself.

Whenever you switch Node.js versions using NVM, the environment changes to use binaries specific to that version. However, npm installs modules globally based on its configuration. The shared ~/node_modules/ directory suggests that your npm configuration might be modified to a custom prefix. To inspect this, you can run:

npm config get prefix

If the prefix is set to something generic like ~/, that's the culprit. To ensure that npm installs packages in a version-specific manner, reset the prefix for each Node.js version:

# While using the intended Node.js version
nvm use <version>
npm config set prefix "$NVM_INSTALLATION_LOCATION/node_modules"

Make certain replace $NVM_INSTALLATION_LOCATION with the appropriate path for your NVM Node.js version directory.

By reconfiguring npm, you'll ensure separation and alignment of modules with the specific Node.js version you are operating.