温馨提示×

Debian JS开发环境怎样搭建

小樊
34
2025-12-11 04:17:08
栏目: 编程语言

在 Debian 上搭建 JavaScript 开发环境

一 准备系统与基础工具

  • 更新索引并安装常用工具:sudo apt update && sudo apt install -y curl wget git build-essential
  • 可选:安装 VS Code(桌面环境)以便高效开发:sudo apt update && sudo apt install -y code
  • 说明:桌面环境可选;服务器场景可仅使用终端与编辑器(如 vim/nano)。

二 安装 Node.js 与 npm

  • 方式 A(系统仓库,简单稳定):sudo apt install -y nodejs npm,随后用 node -v、npm -v 验证版本
  • 方式 B(NodeSource 指定版本,推荐):
    • 选择版本并添加源(示例为 20.x):curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
    • 安装:sudo apt-get install -y nodejs
  • 方式 C(NVM 多版本管理,便于切换):
    • 安装:curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
    • 加载:source ~/.bashrc(或 ~/.zshrc)
    • 使用:nvm install --lts;nvm use --lts;nvm alias default node

三 配置 npm 与全局包路径

  • 提升安装速度与稳定性(可选,中国大陆):npm config set registry https://registry.npmmirror.com
  • 避免全局包写入系统目录(可选,更安全):
    • 创建目录:mkdir -p ~/.npm-global
    • 配置前缀:npm config set prefix ‘~/.npm-global’
    • 写入 PATH:echo ‘export PATH=~/.npm-global/bin:$PATH’ >> ~/.bashrc && source ~/.bashrc
  • 验证:npm config get registry;which npm;npm -v。

四 创建项目与常用工具

  • 初始化与依赖管理:
    • mkdir my-js-project && cd $_
    • npm init -y
    • npm install express
  • 最小 HTTP 服务示例(保存为 server.js):
    • const http = require(‘http’); const hostname = ‘127.0.0.1’; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader(‘Content-Type’, ‘text/plain’); res.end(‘Hello World\n’); }); server.listen(port, hostname, () => { console.log(Server running at http://${hostname}:${port}/); });
    • 运行:node server.js;浏览器访问 http://127.0.0.1:3000
  • 常用开发工具:
    • 全局工具:sudo npm install -g nodemon(热重载开发)
    • 进程守护:sudo npm install -g pm2;常用命令:pm2 start server.js、pm2 list、pm2 logs、pm2 restart server.js

五 部署与反向代理(可选)

  • 安装与配置 Nginx 反向代理到 3000 端口:
    • 安装:sudo apt install -y nginx
    • 编辑站点配置(示例):sudo nano /etc/nginx/sites-available/default
    • 配置片段:
      • server { listen 80; server_name your_domain_or_ip; 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
  • 访问验证:打开浏览器访问 http://your_domain_or_ip

0