diff --git "a/\351\255\217\351\212\256\346\263\223/20260316-\345\206\205\347\275\256\346\250\241\345\235\227.md" "b/\351\255\217\351\212\256\346\263\223/20260316-\345\206\205\347\275\256\346\250\241\345\235\227.md" new file mode 100644 index 0000000000000000000000000000000000000000..652720a334ecce15fcde97dbc9557e5e4d1c571f --- /dev/null +++ "b/\351\255\217\351\212\256\346\263\223/20260316-\345\206\205\347\275\256\346\250\241\345\235\227.md" @@ -0,0 +1,142 @@ +# Node.js内置模块技术解析 + +## 内置模块概述 + +### 核心特性 + +- 技术优势 + - 零依赖:无需额外安装,直接使用 + - 性能优化:经过V8引擎深度优化 + - 功能完备:覆盖常见开发场景 + - 稳定性高:Node.js核心团队维护 + +## 核心模块详解 + +### console模块 + +#### 基础输出功能 + +```javascript +const console = require('console'); + +// 标准输出方法 +console.log('Hello World'); // 普通信息输出 +console.info('这是一条信息'); // 信息级输出 +console.warn('这是一条警告'); // 警告级输出 +console.error('这是一条错误'); // 错误级输出 + +// 模板字符串输出 +const name = '张三'; +console.log(`你好,${name}!`); +``` + +#### 格式化输出 + +- `%s`:字符串占位符 +- `%d`:数字占位符 +- `%j`:JSON对象占位符 + +#### 高级功能 + +```javascript +// 表格形式输出 +console.table([ + { name: '张三', age: 20 }, + { name: '李四', age: 25 } +]); + +// 计数器功能 +console.count('执行次数'); + +// 性能计时 +// 测量循环执行性能 +console.time('loop'); +for (let i = 0; i < 10000; i++) {} +console.timeEnd('loop'); + +// 断言功能 +console.assert(1 === 1, '这不会显示'); +console.assert(1 === 2, '这会显示'); + +// 调用栈追踪 +function fn1() { fn2(); } +function fn2() { console.trace('调用追踪'); } +fn1(); +``` + +### process模块 + +#### 进程信息获取 + +```javascript +// Node.js版本信息 +console.log(process.version); // v24.x.x +console.log(process.versions.node); // 24.x.x +console.log(process.versions.v8); // x.x.x + +// 运行平台信息 +console.log(process.platform); // win32 / darwin / linux +console.log(process.arch); // x64 / arm64 + +// 当前工作目录 +console.log(process.cwd()); // 返回当前工作目录路径 + +// 环境变量 +console.log(process.env.USER); // 用户名 +console.log(process.env.NODE_ENV); // 环境变量设置 +``` + +#### 进程控制 + +```javascript +// 程序退出 +process.exit(0); // 正常退出(退出码0) +process.exit(1); // 异常退出(非零退出码) + +// 退出信号监听 +process.on('exit', (code) => { + console.log('程序即将退出,退出码:' + code); +}); + +process.on('SIGINT', () => { + console.log('收到Ctrl+C信号'); + process.exit(0); +}); + +// 未捕获异常处理 +process.on('uncaughtException', (err) => { + console.error('未捕获的异常:', err); + process.exit(1); +}); +``` + +#### 命令行参数处理 + +```javascript +// 执行命令:node app.js one two three + +console.log(process.argv); +// 输出结构: +// [ +// 'node可执行文件路径', +// '脚本文件路径', +// 'one', +// 'two', +// 'three' +// ] + +// 提取有效参数 +const args = process.argv.slice(2); +console.log(args); // ['one', 'two', 'three'] + +// 解析命令行选项 +const options = {}; +for (let i = 0; i < args.length; i++) { + if (args[i].startsWith('--')) { + const key = args[i].slice(2); + options[key] = args[i + 1]; + i++; + } +} +console.log(options); +``` \ No newline at end of file diff --git "a/\351\255\217\351\212\256\346\263\223/20260318-\345\206\205\347\275\256\346\250\241\345\235\2272.md" "b/\351\255\217\351\212\256\346\263\223/20260318-\345\206\205\347\275\256\346\250\241\345\235\2272.md" new file mode 100644 index 0000000000000000000000000000000000000000..290891e6cf42c90f7a69a81e2f2a1189b9c6a185 --- /dev/null +++ "b/\351\255\217\351\212\256\346\263\223/20260318-\345\206\205\347\275\256\346\250\241\345\235\2272.md" @@ -0,0 +1,49 @@ +# Node.js内置模块进阶 + +## Buffer模块 + +### Buffer核心概念 + +Buffer是Node.js中用于处理二进制数据的核心模块 + +- 应用场景 + - 文件I/O操作 + - 网络数据传输 + - 图像处理 + - 加密解密算法 + +Buffer是Node.js特有的数据类型,本质是一段固定长度的内存空间,存储0-255范围的字节数据,类似于整数数组但专为二进制数据优化 + +## path模块 + +### 路径操作核心功能 + +```javascript +const path = require('path'); + +// 目录路径获取 +console.log(__dirname); // 当前文件所在目录的绝对路径 +console.log(process.cwd()); // 当前工作目录的绝对路径 + +// 文件路径获取 +console.log(__filename); // 当前文件的完整绝对路径 + +// 路径拼接 +const fullPath = path.join(__dirname, 'src', 'index.js'); +console.log(fullPath); // 完整拼接路径:.../src/index.js + +// 绝对路径解析 +const absPath = path.resolve('index.js'); +console.log(absPath); // 解析为绝对路径:C:/Users/.../index.js +``` + +### 路径解析API + +- 获取文件名:`path.basename()` +- 获取文件扩展名:`path.extname()` +- 获取目录路径:`path.dirname()` +- 解析路径信息:`path.parse()` - 返回包含路径各部分的对象 +- 路径格式化:`path.format()` - 根据对象生成路径字符串 +- 路径规范化:`path.normalize()` - 处理路径中的`.`和`..` +- 路径分隔符:`path.sep` - 平台特定的路径分隔符 +- 路径分隔符:`path.delimiter` - 环境变量分隔符 \ No newline at end of file diff --git "a/\351\255\217\351\212\256\346\263\223/20260319-\346\226\207\344\273\266\346\250\241\345\235\227.md" "b/\351\255\217\351\212\256\346\263\223/20260319-\346\226\207\344\273\266\346\250\241\345\235\227.md" new file mode 100644 index 0000000000000000000000000000000000000000..ec616b585122a773a119f282978c4c17d2b2f534 --- /dev/null +++ "b/\351\255\217\351\212\256\346\263\223/20260319-\346\226\207\344\273\266\346\250\241\345\235\227.md" @@ -0,0 +1,145 @@ +# Node.js文件系统模块技术解析 + +## 文件系统操作 + +### 文件读取操作 + +#### 同步读取 + +```javascript +const fs = require('fs'); + +// 同步读取文件内容 +const content = fs.readFileSync('./data.txt', 'utf8'); +console.log(content); + +// 通过选项对象指定编码 +const content2 = fs.readFileSync('./data.txt', { encoding: 'utf8' }); + +// 读取二进制文件(如图片) +const buffer = fs.readFileSync('./image.png'); +``` + +#### 异步读取 + +```javascript +const fs = require('fs'); + +// 异步读取文件(回调方式) +fs.readFile('./data.txt', 'utf8', (err, data) => { + if (err) { + console.error('读取失败:', err); + return; + } + console.log('文件内容:', data); +}); + +// 异步读取二进制文件 +fs.readFile('./image.png', (err, buffer) => { + if (err) throw err; + console.log('文件大小:', buffer.length, '字节'); +}); +``` + +### 文件写入操作 + +#### 同步写入 + +```javascript +const fs = require('fs'); + +// 同步写入文件(覆盖模式) +fs.writeFileSync('./data.txt', 'Hello World'); + +// 同步追加写入 +fs.appendFileSync('./log.txt', '新内容\n'); + +// 写入二进制数据 +const buffer = Buffer.from([1, 2, 3, 4]); +fs.writeFileSync('./data.bin', buffer); +``` + +#### 异步写入 + +```javascript +const fs = require('fs'); + +// 异步写入文件 +fs.writeFile('./data.txt', 'Hello World', 'utf8', (err) => { + if (err) throw err; + console.log('写入成功'); +}); + +// 异步追加写入 +fs.appendFile('./log.txt', '新内容\n', (err) => { + if (err) throw err; + console.log('追加成功'); +}); +``` + +### 高级文件操作 + +#### 文件状态检查 + +```javascript +// 同步检查文件是否存在 +const exists = fs.existsSync('./data.txt'); + +// 获取文件状态信息 +const stats = fs.statSync('./data.txt'); +console.log('是否为文件:', stats.isFile()); +console.log('是否为目录:', stats.isDirectory()); +console.log('文件大小:', stats.size, '字节'); +console.log('创建时间:', stats.birthtime); +console.log('修改时间:', stats.mtime); + +// 异步获取文件状态 +fs.stat('./data.txt', (err, stats) => { + if (err) throw err; + console.log('文件大小:', stats.size); +}); +``` + +#### 文件删除 + +```javascript +// 同步删除文件 +fs.unlinkSync('./temp.txt'); + +// 异步删除文件 +fs.unlink('./temp.txt', (err) => { + if (err) throw err; + console.log('删除成功'); +}); +``` + +#### 文件复制 + +```javascript +// 实现文件复制功能 +function copyFile(src, dest) { + const content = fs.readFileSync(src); + fs.writeFileSync(dest, content); +} + +// 调用示例 +// copyFile('./source.txt', './destination.txt'); +``` + +#### 文件重命名与移动 + +```javascript +const fs = require('fs'); + +// 同步重命名文件 +fs.renameSync('./old.txt', './new.txt'); + +// 同步移动文件(跨目录) +fs.renameSync('./file.txt', './backup/file.txt'); + +// 异步版本 +fs.rename('./old.txt', './new.txt', (err) => { + if (err) throw err; + console.log('重命名成功'); +}); +``` \ No newline at end of file diff --git "a/\351\255\217\351\212\256\346\263\223/20260320-http\346\250\241\345\235\227.md" "b/\351\255\217\351\212\256\346\263\223/20260320-http\346\250\241\345\235\227.md" new file mode 100644 index 0000000000000000000000000000000000000000..3b630d30f7e986adffd9c08e5929be87d075e1bc --- /dev/null +++ "b/\351\255\217\351\212\256\346\263\223/20260320-http\346\250\241\345\235\227.md" @@ -0,0 +1,400 @@ +# Node.js HTTP模块技术解析 + +## HTTP模块概述 + +HTTP模块是Node.js核心模块之一,提供了创建Web服务器和发送HTTP请求的能力,是构建网络应用的基础 + +### 核心功能 + +- 服务器创建:使用`http.createServer()`创建HTTP服务器 +- 客户端请求:使用`http.request()`发送HTTP请求 +- 请求处理:解析和处理客户端请求 +- 响应返回:构建和发送服务器响应 + +### HTTP服务器实现 + +```javascript +const http = require('http'); + +// 创建HTTP服务器 +const server = http.createServer((req, res) => { + // 设置响应状态码和响应头 + res.writeHead(200, {'Content-Type': 'text/plain'}); + // 发送响应内容并结束响应 + res.end('Hello World'); +}); + +// 启动服务器监听 +server.listen(3000, () => { + console.log('服务器运行在 http://localhost:3000'); +}); +``` + +**核心对象说明:** +- `req`:请求对象,包含客户端请求信息 +- `res`:响应对象,用于构建和发送服务器响应 + +### HTTP客户端实现 + +#### GET请求发送 + +```javascript +const http = require('http'); + +// 方式1:使用http.get(GET请求简化版) +http.get('http://localhost:3000/api', (res) => { + let data = ''; + // 接收响应数据 + res.on('data', chunk => data += chunk); + // 响应结束处理 + res.on('end', () => { + console.log('响应:', data); + }); +}); + +// 方式2:使用http.request(完整请求配置) +const options = { + hostname: 'localhost', + port: 3000, + path: '/api?name=张三', + method: 'GET', + headers: { + 'Content-Type': 'application/json' + } +}; + +const req = http.request(options, (res) => { + let data = ''; + res.on('data', chunk => data += chunk); + res.on('end', () => { + console.log('响应:', data); + }); +}); + +// 错误处理 +req.on('error', (err) => { + console.error('请求失败:', err); +}); + +// 结束请求 +req.end(); +``` + +#### POST请求发送 + +```javascript +const http = require('http'); + +// 准备POST数据 +const postData = JSON.stringify({ name: '张三', age: 20 }); + +const options = { + hostname: 'localhost', + port: 3000, + path: '/api/users', + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Content-Length': Buffer.byteLength(postData) + } +}; + +const req = http.request(options, (res) => { + let data = ''; + res.on('data', chunk => data += chunk); + res.on('end', () => { + console.log('响应:', data); + }); +}); + +// 错误处理 +req.on('error', (err) => { + console.error('请求失败:', err); +}); + +// 写入请求数据 +req.write(postData); +// 结束请求 +req.end(); +``` + +### 高级特性 + +#### 路由处理 + +```javascript +const http = require('http'); +const url = require('url'); + +const server = http.createServer((req, res) => { + const parsedUrl = url.parse(req.url, true); + const path = parsedUrl.pathname; + const method = req.method; + + // 路由处理 + if (method === 'GET' && path === '/') { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('首页'); + } else if (method === 'GET' && path === '/api') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ message: 'API响应' })); + } else { + res.writeHead(404, { 'Content-Type': 'text/plain' }); + res.end('404 Not Found'); + } +}); + +server.listen(3000); +``` + +#### 静态文件服务 + +```javascript +const http = require('http'); +const fs = require('fs'); +const path = require('path'); + +const server = http.createServer((req, res) => { + // 处理静态文件请求 + let filePath = path.join(__dirname, 'public', req.url === '/' ? 'index.html' : req.url); + + // 读取文件 + fs.readFile(filePath, (err, content) => { + if (err) { + res.writeHead(404); + res.end('File not found'); + } else { + // 根据文件类型设置Content-Type + const extname = path.extname(filePath); + const contentType = { + '.html': 'text/html', + '.js': 'text/javascript', + '.css': 'text/css', + '.json': 'application/json' + }[extname] || 'application/octet-stream'; + + res.writeHead(200, { 'Content-Type': contentType }); + res.end(content, 'utf8'); + } + }); +}); + +server.listen(3000); +``` +// 20260320-http模块.md +# Node.js HTTP模块技术解析 + +## HTTP模块概述 + +Node.js的http模块提供了完整的HTTP服务器和客户端功能,使开发者能够轻松构建Web应用和进行HTTP通信 + +### 核心功能 + +- 服务器创建:使用`http.createServer()`创建HTTP服务器 +- 客户端请求:使用`http.request()`发送HTTP请求 +- 请求处理:解析和处理客户端请求 +- 响应返回:构建和发送HTTP响应 + +### HTTP服务器创建 + +```javascript +const http = require('http'); + +// 创建HTTP服务器 +const server = http.createServer((req, res) => { + // 设置响应状态码和响应头 + res.writeHead(200, { 'Content-Type': 'text/plain' }); + // 发送响应内容并结束 + res.end('Hello world'); +}); + +// 启动服务器监听 +server.listen(3000, () => { + console.log('服务器运行在 http://localhost:3000'); +}); +``` + +**核心对象说明:** +- `req`:请求对象,包含客户端请求信息(只读) +- `res`:响应对象,用于构建和发送服务器响应(可写) + +### HTTP客户端 + +#### 发送GET请求 + +```javascript +const http = require('http'); + +// 方式1:使用http.get(简化版,适用于GET请求) +http.get('http://localhost:3000/api', (res) => { + let data = ''; + // 接收响应数据 + res.on('data', chunk => data += chunk); + // 响应结束处理 + res.on('end', () => { + console.log('响应:', data); + }); +}); + +// 方式2:使用http.request(完整版,支持所有HTTP方法) +const options = { + hostname: 'localhost', + port: 3000, + path: '/api?name=张三', + method: 'GET', + headers: { + 'Content-Type': 'application/json' + } +}; + +const req = http.request(options, (res) => { + let data = ''; + res.on('data', chunk => data += chunk); + res.on('end', () => { + console.log('响应:', data); + }); +}); + +// 错误处理 +req.on('error', (err) => { + console.error('请求失败:', err); +}); + +// 结束请求(必须调用) +req.end(); +``` + +#### 发送POST请求 + +```javascript +const http = require('http'); + +// 准备POST数据 +const postData = JSON.stringify({ name: '张三', age: 20 }); + +const options = { + hostname: 'localhost', + port: 3000, + path: '/api/users', + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Content-Length': Buffer.byteLength(postData) + } +}; + +const req = http.request(options, (res) => { + let data = ''; + res.on('data', chunk => data += chunk); + res.on('end', () => { + console.log('响应:', data); + }); +}); + +// 错误处理 +req.on('error', (err) => { + console.error('请求失败:', err); +}); + +// 写入请求数据 +req.write(postData); +// 结束请求 +req.end(); +``` + +## 作业 + +### 选择题 + +1. 创建一个HTTP服务器需要使用哪个模块? + B. http + +2. 获取请求的方法(GET、POST)应该访问哪个属性? +B. req.method + +3. 设置响应状态码使用哪个属性? +B. res.statusCode + +4. 返回JSON数据需要设置什么响应头? + B. 'Content-Type': 'application/json' + +5. 使用哪个方法发送响应? +C. res.end() + +### 简答题 + +1. 请解释req和res分别代表什么 +req:表示客户端的请求,只读 +res:表示服务器的响应,可写 + +2. http.createServer的回调函数接收哪些参数? +res req + +3. 如何获取URL中的查询参数? +使用req.url + +4. res.writeHead和res.setHeader有什么区别? +writeHead:一次性设置状态码和多个响应头,并发送响应头 +setHeader:单独设置单个响应头 + +5. http.get和http.request有什么区别? +get:仅支持GET请求,自动调用`req.end()` +request:支持所有HTTP方法,必须手动调用`req.end()` + +### 操作题 + +```js +// app.js +import http from 'http'; +import { rest } from './restful.js'; + +const app = http.createServer((req, res) => { + res.writeHead(200, { 'content-type': 'text/html;charset=utf8' }); + // let content = ''; + // let path = req.url; + // console.log(req.url); + // if (path == '/') { + // content = '这是我的第一个网站'; + // } else if (path == '/about') { + // content = '关于'; + // } else if (path == '/contact') { + // content = '1111'; + // } else { + // content = '404404040404040404'; + // } + let content = rest(req); + res.end(content); +}) + + +let port = 3000; +app.listen(port, () => { + console.log(`服务器运行在如下地址,请善加使用:http://localhost:${port}`); +}); + + + +// restful.js +export function rest(req){ + let method = req.method; + let path = req.url; + + let content = ''; + + if (method == 'GET' && path == '/api/blogs') { + content = '获取博客列表'; + } else if (method == 'GET' && path == '/api/blogs/2') { + content = '获取指定Id的博客'; + } else if (method == 'POST' && path == '/api/blogs') { + content = '新增博客'; + } else if (method == 'PUT' && path == '/api/blogs/2') { + content = '修改博客'; + } else if (method == 'DELETE' && path == '/api/blogs/2') { + content = '删除指定博客'; + } else { + content = '无操作'; + } + + return content; +} +``` \ No newline at end of file