Installing Node.js and npm on Debian
Before managing Node.js modules, you need to install Node.js and its default package manager, npm. On Debian, the easiest way is to use the official NodeSource repository for the latest stable versions:
sudo apt update.lts with a specific version like 16.x if needed):curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs.node -v # Checks Node.js version
npm -v # Checks npm version
This ensures you have the latest Node.js and npm versions compatible with Debian.
Using npm for Module Management
npm (Node Package Manager) is the default tool for managing Node.js modules. Below are core operations:
package.json file to track dependencies. Navigate to your project directory and run:npm init -y # Auto-generates package.json with default settings
node_modules and package.json):npm install express --save # --save is optional (default in npm 5+)
nodemon):sudo npm install -g nodemon # Requires sudo for global access
npm update
To update a specific module (e.g., express):npm update express
package.json:npm uninstall express
For global modules:sudo npm uninstall -g nodemon
npm list --depth=0 # Shows top-level dependencies only
For global modules:npm list -g --depth=0
These commands help manage dependencies efficiently and keep your project organized.
Using Yarn for Module Management
Yarn is an alternative to npm, offering faster installations and deterministic dependency resolution. To use Yarn on Debian:
sudo npm install -g yarn
package.json file (similar to npm):yarn init -y
package.json and generates a yarn.lock file for version locking):yarn add express
yarn global add nodemon
yarn upgrade
To update a specific module (e.g., express):yarn upgrade express
package.json/yarn.lock:yarn remove express
For global modules:yarn global remove nodemon
yarn list --depth=0
For global modules:yarn list -g --depth=0
Yarn’s yarn.lock file ensures consistent dependency versions across environments, making it a popular choice for team projects.
Managing Node.js Versions with nvm
If you need to switch between multiple Node.js versions (e.g., for testing compatibility), use nvm (Node Version Manager):
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
Reload your terminal or run source ~/.nvm/nvm.sh to apply changes.nvm install 16.13.0 # Specific version
nvm install --lts # Latest LTS version
nvm use to activate a version for the current session:nvm use 16.13.0
nvm alias default 16.13.0
nvm ls
nvm is essential for developers working on projects that require different Node.js versions, ensuring compatibility without conflicts.