Node.js 入门学习

Node.js 是基于 Chrome V8 引擎的 JavaScript 运行时环境,允许开发者使用 JavaScript 编写服务器端代码,实现前后端语言统一。

核心基础

环境搭建

下载安装
Node.js 官网 下载对应系统版本
验证安装
打开终端,输入以下命令,若显示版本号则安装成功:
node -v # 查看 Node.js 版本 npm -v # 查看npm版本
第一个 Node.js 程序
创建文件 hello.js,写入代码:console.log("Hello Node.js!");
终端执行:node hello.js,终端输出 Hello Node.js! 即运行成功。

Node.js 与 JavaScript、Java 的差异

对比维度 Node.js 浏览器端 JavaScript Java
运行环境 服务器端 浏览器端 JVM
核心用途 后端开发、工具开发 前端交互 企业级应用、跨平台开发
类型机制 弱类型 弱类型 强类型
编程模式 事件驱动、非阻塞 I/O DOM/BOM 操作、事件驱动 面向对象、多线程
包管理 npm/yarn npm/yarn Maven/Gradle

核心模块学习

Node.js 内置多个核心模块,无需安装即可使用,通过 require() 引入

全局对象与模块系统

常用全局对象

__dirname,当前模块所在目录的绝对路径

__filename,当前模块文件的绝对路径

console,控制台输出

process,进程相关信息

模块导出与引入

Node.js 遵循 CommonJS 模块规范

导出模块

1
2
3
4
5
6
7
8
//方式1,导出单个对象/函数
module.exports = {
add: (a, b) => a + b,
sayHello: () => console.log("Hello Module!")
};

//方式2,逐个导出
exports.sub = (a, b) => a - b;

引入模块

1
2
3
4
5
6
//引入自定义模块
const myModule = require("./myModule.js");
console.log(myModule.add(1, 2)); // 输出 3
myModule.sayHello(); // 输出 Hello Module!
//引入核心模块
const fs = require("fs");

文件系统模块(fs)

用于操作本地文件,支持同步和异步两种方式,入门重点掌握异步操作

常用异步方法

读取文件
fs.readFile(path, [options], callback)const fs = require("fs");

1
2
3
4
5
6
7
8
// 读取 txt 文件
fs.readFile("./test.txt", "utf8", (err, data) => {
if (err) {
console.error("读取失败:", err);
return;
}
console.log("文件内容:", data);
});

写入文件
fs.writeFile(path, data, [options], callback),写入内容到文件,覆盖原有内容

1
2
3
4
5
6
7
fs.writeFile("./test.txt", "Hello fs module!", (err) => {
if (err) {
console.error("写入失败:", err);
return;
}
console.log("写入成功!");
});

HTTP 模块

用于创建 HTTP 服务器,实现简单的 Web 服务功能,是 Node.js 后端开发的基础。

创建简单 Web 服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const http = require("http");
const server = http.createServer((req, res) => {
//响应头
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
if (req.url === "/") {
res.end("欢迎访问首页!");
} else if (req.url === "/about") {
res.end("关于Node.js 入门");
} else {
res.writeHead(404);
res.end("404 页面未找到");
}
});

server.listen(3000, () => {
console.log("服务器已启动,http://localhost:3000");
});

运行代码后,打开浏览器访问 http://localhost:3000 即可看到对应内容。

异步编程基础

Node.js 核心特性是异步非阻塞 I/O,避免传统同步编程的性能瓶颈

回调函数
最基础方式,注意避免“回调地狱”
Promise
封装异步操作,通过 .then() 处理成功结果,.catch() 处理错误。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 用 Promise 封装 fs 读取文件
const readFilePromise = (path) => {
return new Promise((resolve, reject) => {
fs.readFile(path, "utf8", (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
};

// 使用 Promise
readFilePromise("./test.txt")
.then(data => console.log("文件内容:", data))
.catch(err => console.error("错误:", err));

async/await
Promise 的语法糖,让异步代码更接近同步写法。

1
2
3
4
5
6
7
8
9
10
11
// 结合 async/await 使用
const readFileAsync = async () => {
try {
const data = await readFilePromise("./test.txt");
console.log("文件内容:", data);
} catch (err) {
console.error("错误:", err);
}
};

readFileAsync();

npm 包管理

npm 是 Node.js 自带的包管理工具,用于下载、管理第三方依赖包,核心命令:

初始化项目,生成 package.json 文件,npm init
安装指定包npm install 包名
安装日志包 log4js,npm install log4js
全局安装npm install 包名 -g
卸载指定包npm uninstall 包名

使用第三方包
安装完成后,通过 require() 引入即可使用。

1
2
3
const log4js = require("log4js");
const logger = log4js.getLogger();
logger.info("这是一条日志信息");

练习

结合核心模块做综合练,实现一个“文件内容展示服务”,通过浏览器访问指定路径,展示本地txt文件内容。

需求说明

启动 HTTP 服务器,监听 3000 端口。
访问 http://localhost:3000/file,返回本地 data.txt 文件的内容。
若文件不存在或读取失败,返回 500 错误提示。
访问其他路径,返回 404 提示。

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

const http = require("http");
const fs = require("fs");

// 封装 Promise 版读取文件函数
const readFile = (path) => {
return new Promise((resolve, reject) => {
fs.readFile(path, "utf8", (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
};

// 创建服务器
const server = http.createServer(async (req, res) => {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
if (req.url === "/file") {
try {
const data = await readFile("./data.txt");
res.end("文件内容:\n" + data);
} catch (err) {
res.writeHead(500);
res.end("错误:读取文件失败 - " + err.message);
}
} else {
res.writeHead(404);
res.end("404 页面未找到");
}
});

// 启动服务器
server.listen(3000, () => {
console.log("服务器已启动:http://localhost:3000");
});

测试步骤

创建 data.txt 文件,写入任意内容
运行代码:node server.js
浏览器访问 http://localhost:3000/file,查看文件内容;访问 http://localhost:3000/other,查看 404 提示

总结

事件驱动、非阻塞 I/O,适合高并发场景
掌握核心模块、模块系统、异步编程逻辑
学习 Express/Koa 框架、数据库操作、RESTful API 设计等

学习资源

官方文档,Node.js 中文文档
入门教程,Node.js 菜鸟教程、B站 Node.js 入门视频
实战项目,GitHub “nodejs beginner projects”