Debian 下 JavaScript 环境配置指南
一 安装 Node.js 与 npm
sudo apt update
sudo apt install -y nodejs npm
node -v
npm -v
# LTS
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
# 或指定版本,例如 20.x
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
node -v
npm -v
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
# 重新加载 shell 配置
source ~/.bashrc # 或 source ~/.zshrc
# 安装与切换
nvm install --lts
nvm use --lts
node -v
npm -v
以上三种方式按需选择:追求稳定与简单用系统仓库;需要新版本或精确版本用 NodeSource;需要多版本并存与快速切换用 NVM。
二 配置 npm 与全局路径
mkdir -p ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
npm config get prefix
which npm
npm config set registry https://registry.npmmirror.com
npm config get registry
以上步骤完成后,全局安装的 CLI 工具(如 npm、yarn、pm2)将位于用户目录,无需 sudo 即可使用。
三 创建项目与常用工具
mkdir my-js-project && cd $_
npm init -y
npm install express
cat > index.js <<'EOF'
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send('Hello World'));
app.listen(port, () => console.log(`App listening on http://localhost:${port}`));
EOF
node index.js
npm install -g pm2
pm2 start index.js --name myapp
pm2 list
pm2 logs
pm2 startup # 按提示完成开机自启
sudo apt install -y yarn
yarn init -y
yarn add express
以上覆盖了最常见的项目初始化、依赖安装、运行与进程管理场景。
四 反向代理与端口开放(可选)
sudo apt install -y nginx
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
sudo nginx -t
sudo systemctl reload nginx
sudo ufw allow 80,443/tcp
sudo ufw enable
上述配置适合将 Node 应用以域名方式对外提供访问,并与静态资源服务解耦。