在 Debian 上配置 Node.js,通常包含安装 Node.js / npm、版本管理(可选)、环境变量与镜像配置、以及常见服务化运行方式。下面按实用场景一步步说明。
sudo apt update
sudo apt install -y nodejs npm
查看版本:
node -v
npm -v
以 Node.js 20.x 为例:
sudo apt update
sudo apt install -y curl
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
验证:
node -v
npm -v
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install --lts
node -v
npm config set registry https://registry.npmmirror.com
查看:
npm config get registry
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
添加到 ~/.bashrc:
export PATH=~/.npm-global/bin:$PATH
然后:
source ~/.bashrc
node app.js
sudo npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup
示例:/etc/systemd/system/node-app.service
[Unit]
Description=Node.js App
After=network.target
[Service]
User=www-data
WorkingDirectory=/var/www/node-app
ExecStart=/usr/bin/node app.js
Restart=always
[Install]
WantedBy=multi-user.target
启用:
sudo systemctl daemon-reload
sudo systemctl enable node-app
sudo systemctl start node-app
node: command not foundwhich nodesudo setcap cap_net_bind_service=+ep /usr/bin/node
cnpm:npm install -g cnpm --registry=https://registry.npmmirror.com
如果你能告诉我:
我可以给你更精确的配置方案。