Linux 上配置 JS 开发环境
一 安装 Node.js 与 npm
sudo apt update
sudo apt install -y nodejs npm
sudo yum update -y
sudo yum install -y nodejs npm
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs
# 或指定 18.x
# curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
# sudo apt install -y nodejs
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc # 若使用 zsh 则 source ~/.zshrc
nvm ls-remote
nvm install 18.16.1
nvm alias default 18.16.1
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 set registry https://registry.npmmirror.com
npm config get registry # 验证
npm install -g yarn pm2 nodemon typescript
echo 'export PATH=/usr/local/nodejs/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
以上配置可有效避免权限问题、提升安装速度,并便于多用户与多项目统一工具链管理。
三 第一个 Node.js 应用与进程守护
mkdir myapp && cd myapp
npm init -y
npm install express
cat > app.js <<'EOF'
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello from Linux & Node.js'));
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
EOF
node app.js
npm install -g pm2
pm2 start app.js --name myapp
pm2 status
pm2 logs myapp
四 常见问题与排查
source ~/.bashrc 或重登终端。nvm use。