Node.js 基础教程
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境,让 JavaScript 可以脱离浏览器运行在服务器端。本教程将从环境搭建到核心知识点,带你快速掌握 Node.js 基础。
一、环境搭建
1. 下载与安装
-
官方下载:访问 Node.js 官网,推荐下载 LTS(长期支持版),适配 Windows/macOS/Linux 系统。
-
验证安装:安装完成后,打开终端 / 命令提示符,执行以下命令,若输出版本号则安装成功:
node -v # 查看 Node.js 版本 npm -v # 查看 npm(包管理工具)版本
2. 可选:nvm 版本管理(推荐)
若需切换多个 Node.js 版本,可使用 nvm(Node Version Manager):
-
安装 nvm:参考 nvm 官网
-
常用命令:
nvm install 20.10.0 # 安装指定版本 nvm use 20.10.0 # 切换到指定版本 nvm list # 查看已安装版本
二、第一个 Node.js 程序
1. 新建文件
创建 hello.js,写入以下代码:
// 控制台输出
console.log("Hello, Node.js!");
// 读取命令行参数
console.log("命令行参数:", process.argv);
2. 运行程序
在终端进入文件所在目录,执行:
node hello.js
输出结果:
Hello, Node.js!
命令行参数: [ '/usr/local/bin/node', '/Users/xxx/hello.js' ]
三、核心模块
Node.js 内置了大量核心模块,无需安装即可使用,以下是最常用的几个:
1. fs 模块(文件系统)
用于读写文件、操作目录,支持同步 / 异步两种方式(推荐异步,避免阻塞)。
异步读取文件
const fs = require('fs');
// 异步读取文件(非阻塞)
fs.readFile('./test.txt', 'utf8', (err, data) => {
if (err) {
console.error('读取失败:', err);
return;
}
console.log('文件内容:', data);
});
// 异步写入文件(覆盖写入)
fs.writeFile('./test.txt', 'Hello, fs!', (err) => {
if (err) throw err;
console.log('文件写入成功!');
});
同步读取文件
// 同步读取(阻塞,慎用)
const data = fs.readFileSync('./test.txt', 'utf8');
console.log('同步读取:', data);
2. path 模块(路径处理)
解决不同系统路径分隔符(Windows ``、Linux/macOS /)的兼容问题。
const path = require('path');
// 拼接路径
const fullPath = path.join(__dirname, 'src', 'app.js');
console.log('拼接路径:', fullPath);
// 获取文件扩展名
const ext = path.extname('app.js');
console.log('文件扩展名:', ext); // .js
// 获取文件名(不含扩展名)
const baseName = path.basename('app.js', '.js');
console.log('文件名:', baseName); // app
__dirname:当前文件所在目录的绝对路径__filename:当前文件的绝对路径
3. http 模块(创建 HTTP 服务器)
Node.js 最核心的用途之一是搭建服务器,http 模块无需框架即可快速创建:
const http = require('http');
// 创建服务器
const server = http.createServer((req, res) => {
// 设置响应头
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
// 响应内容
res.end('你好,Node.js HTTP 服务器!\n');
});
// 监听端口
const port = 3000;
server.listen(port, () => {
console.log(`服务器运行在 http://localhost:${port}`);
});
运行后访问 http://localhost:3000,即可看到响应内容。
4. url 模块(URL 解析)
解析 URL 字符串,提取协议、主机、路径等信息:
const url = require('url');
const urlStr = 'http://localhost:3000/user?id=100&name=张三';
const parsedUrl = url.parse(urlStr, true); // true 解析 query 为对象
console.log('协议:', parsedUrl.protocol); // http:
console.log('路径:', parsedUrl.pathname); // /user
console.log('查询参数:', parsedUrl.query); // { id: '100', name: '张三' }
四、模块化开发
Node.js 采用 CommonJS 模块化规范,核心规则:
- 每个文件是一个独立模块
module.exports导出模块内容require()导入其他模块
1. 导出模块
创建 math.js:
// 定义函数
const add = (a, b) => a + b;
const mul = (a, b) => a * b;
// 方式1:批量导出
module.exports = {
add,
mul
};
// 方式2:单独导出
// module.exports.add = add;
// module.exports.mul = mul;
2. 导入模块
创建 main.js:
// 导入自定义模块(相对路径)
const math = require('./math.js');
console.log('1+2=', math.add(1, 2)); // 3
console.log('2×3=', math.mul(2, 3)); // 6
// 导入核心模块(无需路径)
const fs = require('fs');
// 导入第三方模块(先 npm 安装)
// const axios = require('axios');
五、npm 包管理工具
npm 是 Node.js 自带的包管理工具,用于安装、管理第三方依赖包。
1. 常用命令
npm init -y # 快速初始化 package.json(项目配置文件)
npm install 包名 # 安装包到当前项目(生产依赖)
npm i 包名 -S # 同上(简写)
npm i 包名 -D # 安装开发依赖(如 eslint、webpack)
npm i 包名 -g # 全局安装(如 nodemon、vue-cli)
npm uninstall 包名 # 卸载包
npm list # 查看已安装包
npm run 脚本名 # 运行 package.json 中的 scripts 脚本
2. 示例:安装并使用 axios
# 初始化项目
npm init -y
# 安装 axios
npm install axios
创建 axios-demo.js:
const axios = require('axios');
// 发送 GET 请求
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
console.log('响应数据:', response.data);
})
.catch(error => {
console.error('请求失败:', error);
});
3. 开发便捷工具:nodemon
全局安装 nodemon,修改代码后自动重启服务:
npm install nodemon -g
# 运行文件(替代 node 命令)
nodemon app.js
六、异步编程
Node.js 核心是异步非阻塞,常用异步处理方式:
1. 回调函数(基础)
// 示例:读取文件(回调函数)
fs.readFile('./test.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
2. Promise
解决回调地狱问题:
const fs = require('fs').promises; // 新版 fs 内置 Promise 版本
// 使用 Promise 读取文件
fs.readFile('./test.txt', 'utf8')
.then(data => {
console.log(data);
})
.catch(err => {
console.error(err);
});
3. async/await(推荐)
Promise 的语法糖,同步写法实现异步:
const fs = require('fs').promises;
// 异步函数
async function readFileAsync() {
try {
const data = await fs.readFile('./test.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
// 调用
readFileAsync();
七、常见应用场景
- 后端 API 开发:结合 Express/Koa 框架快速搭建 RESTful API
- 前端工程化:Webpack/Vite/ESLint 等工具基于 Node.js 运行
- 命令行工具开发:如 Vue CLI、Create React App
- 实时应用:结合 Socket.io 开发聊天室、实时监控系统
- 爬虫开发:结合 axios/cheerio 爬取网页数据
八、学习资源
- 官方文档:Node.js 官网文档
- 框架学习:Express(轻量)、Koa(优雅)、Nest.js(企业级)
- 实战项目:搭建个人博客、接口服务、爬虫工具等