Node.js 简介
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时。
什么是 Node.js
Node.js 是一个基于 Chrome V8 JavaScript 引擎的 JavaScript 运行时。Node.js 使用事件驱动、非阻塞 I/O 模型,使其轻量且高效。Node.js 的包生态系统 npm 是世界上最大的开源库生态系统。
Node.js 的特点
Node.js 具有以下特点:事件驱动、非阻塞 I/O、单一线程、跨平台、丰富的 NPM 包。
Node.js 安装
学习如何安装 Node.js。
Windows 安装
从 Node.js 官网下载 LTS 版本安装包,双击运行安装。安装完成后,在命令行输入 node -v 和 npm -v 验证安装。
node -v npm -v
使用 NVM 管理 Node 版本
NVM(Node Version Manager)允许在同一台机器上安装多个 Node.js 版本。
# 安装 NVM curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash # 使用 NVM 安装 Node nvm install node nvm use node
Node.js 模块系统
Node.js 使用模块系统来组织代码。
模块简介
Node.js 模块相当于其他编程语言中的库,一个 Node.js 文件就是一个模块。
// hello.js
module.exports = function() {
console.log("Hello World!");
}require 导入模块
使用 require 函数导入模块。
// main.js
const hello = require("./hello");
hello();exports 导出
使用 exports 对象导出模块成员。
// person.js
exports.name = "Tom";
exports.age = 25;
exports.sayHello = function() {
console.log("Hello!");
}Node.js 函数
在 Node.js 中使用函数。
函数作为参数
在 Node.js 中,函数可以作为参数传递和返回值。
function sayHello(name) {
console.log("Hello, " + name);
}
function execute(fn, name) {
fn(name);
}
execute(sayHello, "Tom");匿名函数
可以创建没有名称的匿名函数。
setTimeout(function() {
console.log("Delayed!");
}, 1000);Node.js 缓冲区
Buffer 类用于操作二进制数据流。
创建缓冲区
使用 Buffer.alloc 和 Buffer.from 创建缓冲区。
const buf = Buffer.alloc(256);
const len = buf.write("Hello World");
console.log("写入字节数: " + len);
console.log(buf.toString());Node.js 流
流是 Node.js 中处理流式数据的核心概念。
流的概念
流是一种处理数据的抽象接口,Node.js 有四种流类型:Readable(可读)、Writable(可写)、Duplex(双工)、Transform(转换)。
const fs = require("fs");
// 创建可读流
const readStream = fs.createReadStream("input.txt");
readStream.on("data", function(chunk) {
console.log("数据块:", chunk);
});
readStream.on("end", function() {
console.log("读取完成");
});Node.js 模块系统
Node.js NPM 包管理。
npm 命令
NPM 是 Node.js 的包管理工具。
# 初始化项目 npm init # 安装包 npm install express # 全局安装 npm install -g nodemon # 安装开发依赖 npm install --save-dev webpack
package.json
package.json 是项目的配置文件,记录了项目依赖等信息。
{
"name": "my-project",
"version": "1.0.0",
"dependencies": {
"express": "^4.18.0"
}
}Node.js Web 服务器
使用 Node.js 创建 Web 服务器。
创建 HTTP 服务器
使用 http 模块创建简单的 Web 服务器。
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, {"Content-Type": "text/html"});
res.end("Hello World!");
});
server.listen(3000, () => {
console.log("服务器运行在 http://localhost:3000/");
});Node.js Express 框架
Express 是最流行的 Node.js Web 框架。
Express 基础
Express 提供了一套简洁的 API 来创建 Web 服务器。
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(3000, () => {
console.log("Express 服务器运行在端口 3000");
});Node.js 路由
路由决定了不同 URL 请求的处理方式。
基本路由
Express 支持 GET、POST、PUT、DELETE 等路由方法。
app.get("/", (req, res) => {
res.send("GET 请求");
});
app.post("/submit", (req, res) => {
res.send("POST 请求");
});
app.put("/update", (req, res) => {
res.send("PUT 请求");
});
app.delete("/delete", (req, res) => {
res.send("DELETE 请求");
});