Node.js 简介与安装
Node.js 让 JavaScript 可以脱离浏览器运行,成为服务端开发语言。
什么是 Node.js
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境:
- 单线程:主线程单线程,通过事件循环处理并发
- 非阻塞 I/O:异步处理,不等待操作完成
- 事件驱动:基于事件机制处理请求
- 跨平台:支持 Windows、Linux、macOS
Node.js 应用场景
| 场景 | 说明 |
|---|---|
| Web 服务器 | Express、Koa、NestJS |
| API 服务 | RESTful API、GraphQL |
| 实时应用 | WebSocket、Socket.io |
| 命令行工具 | CLI 应用、脚手架 |
| 微服务 | 轻量级服务架构 |
| 桌面应用 | Electron 框架 |
| 前端构建 | Webpack、Vite |
安装 Node.js
官网下载安装
Bash
# 下载地址
# https://nodejs.org/
# LTS 版本:长期支持,稳定
# Current 版本:最新功能
# 下载对应系统的安装包,按提示安装
验证安装
Bash
# 查看版本
node -v
# v20.x.x
npm -v
# 10.x.x
包管理器安装
Bash
# macOS (Homebrew)
brew install node
# Linux (apt)
sudo apt install nodejs npm
# Windows (scoop)
scoop install nodejs
# 或使用 nvm 管理(推荐)
使用 nvm 管理版本
Bash
# 安装 nvm
# macOS/Linux: curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# Windows: 下载 nvm-windows
# https://github.com/coreybutler/nvm-windows/releases
# 安装最新 LTS 版本
nvm install --lts
# 安装指定版本
nvm install 18
nvm install 20
# 切换版本
nvm use 18
nvm use 20
# 查看已安装版本
nvm list
# 查看可用版本
nvm ls-remote
# 设置默认版本
nvm alias default 20
推荐使用 nvm 管理 Node.js 版本,方便切换。
运行 JavaScript
Bash
# 运行 JS 文件
node app.js
# REPL 模式(交互式)
node
> console.log('Hello')
Hello
> .exit # 退出
# 执行单行代码
node -e "console.log('Hello')"
# 检查语法
node --check app.js
Node.js 与浏览器区别
| 特性 | Node.js | 浏览器 |
|---|---|---|
| 运行环境 | 服务端 | 客户端 |
| 全局对象 | global | window |
| 模块系统 | CommonJS | ES Modules |
| DOM | 无 | 有 |
| 文件系统 | 有(fs) | 无 |
| 网络请求 | http/net | fetch/XMLHttpRequest |
查看配置信息
Bash
# 查看详细信息
node -p "process.versions"
node -p "process.arch"
node -p "process.platform"
# 查看 Node.js 路径
which node # macOS/Linux
where node # Windows
要点总结
- Node.js 基于 V8 引擎,单线程、非阻塞 I/O、事件驱动
- 官网下载安装或使用包管理器安装
- 推荐使用 nvm 管理多版本 Node.js
- node -v 验证安装,node app.js 运行文件
- Node.js 无 DOM,有文件系统和网络模块
📝 发现内容有误?点击此处直接编辑