如何在 Linux 上搭建 Node.js 开发环境

699
2025/4/7 15:33:13
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在 Linux 上搭建 Node.js 开发环境可以通过以下步骤进行:

1. 安装 Node.js

使用 NodeSource 二进制分发库

  • Ubuntu/Debian:

    1. 安装 NodeSource 库:
      curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
      
    2. 安装 Node.js 和 npm:
      sudo apt-get install -y nodejs
      
  • CentOS/RHEL:

    1. 安装 NodeSource 库:
      curl -fsSL https://rpm.nodesource.com/setup_16.x | sudo -E bash -
      
    2. 安装 Node.js 和 npm:
      sudo yum install -y nodejs
      

使用包管理器

  • Ubuntu/Debian:

    sudo apt-get update
    sudo apt-get install nodejs npm
    
  • CentOS/RHEL:

    sudo yum install -y nodejs npm --enablerepo epel
    

使用 nvm(Node Version Manager)

  1. 安装 nvm:
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
    
  2. 加载 nvm 配置:
    source ~/.bashrc
    
  3. 安装 Node.js:
    nvm install node
    
    或者安装特定版本:
    nvm install 16.14.0
    

2. 配置 npm

  • 安装 npm(如果尚未安装):
    npm install -g npm
    

3. 设置文本编辑器或 IDE

  • 推荐使用 Visual Studio Code、Sublime Text 或 WebStorm 等。

4. 创建项目文件夹并初始化 npm 项目

  1. 创建项目文件夹:
    mkdir mynodeapp
    cd mynodeapp
    
  2. 初始化项目:
    npm init -y
    
  3. 安装依赖项:
    npm install express
    

5. 编写代码并运行应用程序

  1. 创建 server.js 文件并编写代码:
    const express = require('express');
    const app = express();
    app.get('/', (req, res) => {
      res.send('Hello World!');
    });
    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });
    
  2. 运行应用程序:
    node server.js
    
  3. 访问应用: 打开浏览器,输入 http://localhost:3000

6. 额外工具和配置

  • 版本控制系统: 安装 Git:
    sudo apt install git
    
  • 调试工具: 使用 Node.js 调试器或其他调试工具。
  • 构建工具: 如 Webpack、Parcel 等。

通过以上步骤,你可以在 Linux 上成功搭建 Node.js 开发环境。如果遇到问题,可以参考 Node.js 官方文档或社区论坛获取帮助。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: arch linux如何配置图形界面