第一章:Node.js简介与环境搭建

作者:Administrator 发布时间: 2026-03-13 阅读量:0 评论数:0

第一章:Node.js简介与环境搭建

1.1 Node.js是什么?

定义

Node.js是一个基于Chrome V8引擎的JavaScript运行时环境,让JavaScript可以在服务器端运行。

核心特点

特点

说明

单线程

使用事件循环处理并发

非阻塞I/O

异步处理输入输出,不等待

事件驱动

基于事件的编程模型

跨平台

Windows、macOS、Linux都支持

npm生态

全球最大的开源库生态系统

Node.js vs 传统服务器

传统服务器(Apache/PHP):        Node.js:
┌─────────┐                      ┌─────────┐
│ 请求1   │ ──→ 处理 ──→ 响应    │ 请求1   │ ──┐
├─────────┤                      ├─────────┤   │
│ 请求2   │ ──→ 等待 ──→ 响应    │ 请求2   │ ──┼→ 事件循环 → 响应
├─────────┤                      ├─────────┤   │
│ 请求3   │ ──→ 等待 ──→ 响应    │ 请求3   │ ──┘
└─────────┘                      └─────────┘
   阻塞式                           非阻塞式

1.2 安装Node.js

下载安装

Windows/macOS:

  1. 访问 https://nodejs.org/

  2. 下载LTS(长期支持)版本

  3. 双击安装包按向导安装

Linux:

# Ubuntu/Debian
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs
​
# CentOS/RHEL
curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -
sudo yum install -y nodejs
​
# 或使用nvm(推荐)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
source ~/.bashrc
nvm install --lts
nvm use --lts

验证安装

# 查看Node.js版本
node --version
# v20.10.0
​
# 查看npm版本
npm --version
# 10.2.3

1.3 第一个Node.js程序

Hello World

创建文件 hello.js

// hello.js
// 这行代码向控制台输出文本
console.log('Hello, Node.js!');

运行:

node hello.js

输出:

Hello, Node.js!

代码解析

// console 是Node.js提供的全局对象
// log 是console对象的方法,用于输出信息
console.log('Hello, Node.js!');

1.4 使用Node.js交互式环境

# 进入交互式环境
node
​
# 可以直接执行JavaScript代码
> 1 + 1
2
​
> console.log('Hello')
Hello
undefined
​
> const name = 'Node.js'
undefined
​
> name
'Node.js'
​
> .exit  # 退出

1.5 模块系统

CommonJS模块

Node.js使用CommonJS模块规范。

创建模块 (math.js):

// math.js
// 定义加法函数
function add(a, b) {
    return a + b;
}

// 定义减法函数
function subtract(a, b) {
    return a - b;
}

// 导出模块
module.exports = {
    add: add,
    subtract: subtract
};

使用模块 (app.js):

// app.js
// 引入math模块
const math = require('./math.js');

// 使用模块中的函数
console.log(math.add(5, 3));        // 输出: 8
console.log(math.subtract(5, 3));   // 输出: 2

ES6模块(推荐)

创建模块 (math.mjs 或设置 "type": "module"):

// math.mjs
// 导出加法函数
export function add(a, b) {
    return a + b;
}

// 导出减法函数
export function subtract(a, b) {
    return a - b;
}

// 默认导出
export default function multiply(a, b) {
    return a * b;
}

使用模块 (app.mjs):

// app.mjs
// 导入默认导出
import multiply from './math.mjs';

// 导入命名导出
import { add, subtract } from './math.mjs';

console.log(add(5, 3));         // 输出: 8
console.log(subtract(5, 3));    // 输出: 2
console.log(multiply(5, 3));    // 输出: 15

1.6 npm包管理器

初始化项目

# 创建项目目录
mkdir my-project
cd my-project

# 初始化npm项目
npm init -y

生成 package.json

{
  "name": "my-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

安装依赖

# 安装生产依赖
npm install express

# 安装开发依赖
npm install --save-dev nodemon

# 全局安装
npm install -g pm2

# 安装指定版本
npm install express@4.18.0

package.json 详解

{
  "name": "my-project",
  "version": "1.0.0",
  "description": "项目描述",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "test": "jest"
  },
  "dependencies": {
    "express": "^4.18.0"
  },
  "devDependencies": {
    "nodemon": "^3.0.0"
  },
  "engines": {
    "node": ">=18.0.0"
  }
}

常用npm命令

# 安装所有依赖
npm install

# 运行脚本
npm start
npm run dev
npm test

# 更新依赖
npm update

# 卸载依赖
npm uninstall express

# 查看已安装包
npm list

# 查看过期包
npm outdated

1.7 练习

练习1:创建计算器模块

创建一个计算器模块,支持加减乘除四则运算。

练习2:初始化项目

使用npm init初始化一个项目,安装lodash库并使用。


评论