From ac82aed04faaa660002b3f89db1011a3a35e7207 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=B4=E6=B8=8A=E5=8D=9A?= <1914734353@qq.com> Date: Sun, 22 Mar 2026 21:21:53 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AC=94=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...41\345\235\227\347\254\224\350\256\260.md" | 40 +++++ ...05\347\275\256\346\250\241\345\235\227.md" | 156 ++++++++++++++++++ ...73\347\273\237\346\250\241\345\235\227.md" | 106 ++++++++++++ ...20-nodejs HTTP\346\250\241\346\235\277.md" | 109 ++++++++++++ 4 files changed, 411 insertions(+) create mode 100644 "\345\220\264\346\270\212\345\215\232/20260316-nodejs\346\250\241\345\235\227\347\254\224\350\256\260.md" create mode 100644 "\345\220\264\346\270\212\345\215\232/20260318-\345\237\272\347\241\200\345\206\205\347\275\256\346\250\241\345\235\227.md" create mode 100644 "\345\220\264\346\270\212\345\215\232/20260319-\346\226\207\344\273\266\347\263\273\347\273\237\346\250\241\345\235\227.md" create mode 100644 "\345\220\264\346\270\212\345\215\232/20260320-nodejs HTTP\346\250\241\346\235\277.md" diff --git "a/\345\220\264\346\270\212\345\215\232/20260316-nodejs\346\250\241\345\235\227\347\254\224\350\256\260.md" "b/\345\220\264\346\270\212\345\215\232/20260316-nodejs\346\250\241\345\235\227\347\254\224\350\256\260.md" new file mode 100644 index 0000000..78e03ac --- /dev/null +++ "b/\345\220\264\346\270\212\345\215\232/20260316-nodejs\346\250\241\345\235\227\347\254\224\350\256\260.md" @@ -0,0 +1,40 @@ +import fs ,{read} from 'fs' +import { type } from 'os'; + +const Address='./text.json'; + +let command=process.argv[2]; +let params=process.argv[3]; + +if(command=='add'){ + let arr=readFromJson(); + arr.push({ + amount:params*1, + type:'input', + timestamp:new Date() + }) + writeToJson(arr); + printAmount(); +} +else if(command=='del'){ + +} +else if(){} +else if(){} + +function readFromJson(){ + if(fs.existsSync(Address)){ + let jsonString=fs.readFileSync(Address,'utf-8'); + if(jsonString.length>0){ + return JSON.parse(jsonString); + + } + return []; + } + return []; +} + +function writeToJson(arr){ + let jsonString=JSON.stringify(arr); + fs.writeFileSync(Address,jsonString); +} diff --git "a/\345\220\264\346\270\212\345\215\232/20260318-\345\237\272\347\241\200\345\206\205\347\275\256\346\250\241\345\235\227.md" "b/\345\220\264\346\270\212\345\215\232/20260318-\345\237\272\347\241\200\345\206\205\347\275\256\346\250\241\345\235\227.md" new file mode 100644 index 0000000..22e9dfe --- /dev/null +++ "b/\345\220\264\346\270\212\345\215\232/20260318-\345\237\272\347\241\200\345\206\205\347\275\256\346\250\241\345\235\227.md" @@ -0,0 +1,156 @@ +## Node.js内置模块 +- 内置模块特点 +- 无需安装、性能优化、功能强大、稳定可靠。 + +console控制台输出 +用于日志输出、计时(console.time())、表格(console.table())等方法 +process进程管理 +用于获取进程信息、处理命令行参数 +//Node.js版本信息 +console.log(process.version); + +// 平台信息 +console.log(process.platform); + +// 当前工作目录 +console.log(process.cwd()); + +// 环境变量 +console.log(process.env.USER); +Buffer二进制数据 +-用于创建和操作二进制数据 -文件读写 -网络传输 -图片处理 -加密解密 + +path路径处理 +-用于处理文件路径 + +global全局对象 +练习 +选择题 +下面哪个方法可以获取Node.js的版本号? + +B. process.version + +Buffer.alloc(10)创建的Buffer,长度是多少字节? + +A. 10 + +"你好"的Buffer长度是? + +C. 6 + +__dirname表示什么? + +B. 当前文件所在目录 + +console.time()和console.timeEnd()的作用是? + +A. 计时 + +简答题 +请解释console.log和console.error的区别。 + +console.log() 用于一般的日志输出,而 console.error() 专门用于错误信息的输出,具有更明显的视觉标识和不同的输出流。 + +process.argv返回的数组包含哪些内容?请举例说明。 + +第一个元素‌:Node.js 可执行文件的路径 ‌ - 第二个元素‌:正在执行的 JavaScript 文件路径 ‌ - 后续元素‌:传递给脚本的命令行参数 + +Buffer和普通数组有什么区别? + +Buffer 本质上是字节数组,每个元素都是一个字节 +普通数组可以包含任意类型的元素,如整数、字符串等 +__dirname和process.cwd()有什么区别? + +__dirname 总是指向当前脚本文件所在的目录,而 process.cwd() 指向的是执行 Node.js 命令时所在的目录 + +path.join()和path.resolve()有什么区别? + +path.join() 会忽略前面的路径片段,如果遇到绝对路径参数 + +path.resolve() 会以绝对路径为基准,从右向左处理直到构建出绝对路径 + +操作题 +console.log('=== Node.js 信息 ==='); +console.log('版本:', process.version); +console.log('平台:', process.platform); +console.log('架构:', process.arch); + + + +import fs from 'fs' + +let command=process.argv[2]; +let params=process.argv[3]; +const a = parseFloat(process.argv[3]); +const b = parseFloat(process.argv[4]); + + +let c; +if(command==='add'){ + c=a+b; + console.log(`${a}+${b}=${c}`); +} +else if(command=='sub'){ + c=a-b; + console.log(`${a}-${b}=${c}`); +} +else if(command=='mul'){ + c=a*b; + console.log(`${a}*${b}=${c}`); +} + + + +const buf2 = Buffer.from('你好'); +console.log('Buffer字符串长度:', buf2); +console.log('Buffer转字符串:', buf2.toString()); + + + +const path = require('path'); +const filePath = process.argv[2]; +const filename = path.basename(filePath); +const extname = path.extname(filePath); +const dirname = path.dirname(filePath); +const nameWithoutExt = path.basename(filePath, extname); +console.log(`文件名: ${filename}`); +console.log(`不带扩展名的文件名: ${nameWithoutExt}`); +console.log(`扩展名: ${extname}`); +console.log(`所在目录: ${dirname}`); + + + + +if(command=='add'){ + console.log("添加"); + let arr=readFile(); + arr.push({'title':params,'isDone':false}); + writeFile(arr); + let newArr=readFile(); + console.log(newArr); +} +else if(command=='list'){ + console.log("列表"); + let list=readFile(); + console.log(list); +}else if(command=='del'){ + console.log("删除"); + let idx=parseInt(params); + let delArr=readFile(); + delArr.splice(idx-1,1); + writeFile(delArr); +} + +function readFile(filePath){ + filePath=filePath||'./text.json'; + if(fs.existsSync(filePath)){ + let data=fs.readFileSync(filePath,'utf-8'); + return JSON.parse(data)||[]; + } + return []; +} +function writeFile(fileContent,filePath){ + filePath=filePath||'./text.json'; + let jsonString=JSON.stringify(fileContent); + fs.writeFileSync(filePath,jsonString); +} \ No newline at end of file diff --git "a/\345\220\264\346\270\212\345\215\232/20260319-\346\226\207\344\273\266\347\263\273\347\273\237\346\250\241\345\235\227.md" "b/\345\220\264\346\270\212\345\215\232/20260319-\346\226\207\344\273\266\347\263\273\347\273\237\346\250\241\345\235\227.md" new file mode 100644 index 0000000..d8b6432 --- /dev/null +++ "b/\345\220\264\346\270\212\345\215\232/20260319-\346\226\207\344\273\266\347\263\273\347\273\237\346\250\241\345\235\227.md" @@ -0,0 +1,106 @@ +## 文件系统 +- fs模块 +- 特点:功能完善、两种方式(同步(带Sync)和异步(回调/Promise))、流式处理、权限控制 +- 读取文件 +- 同步读取 + +- 异步读取 + +- 回调方式 + - Promise方式 + - 写入文件 + - 同步写入 +fs.writeFileSync('./data.txt', 'Hello World'); + + + +- 异步写入 +```js +fs.writeFile('./data.txt', 'Hello World', 'utf8', (err) => { + if (err) throw err; + console.log('写入成功'); +}); +创建目录 +删除文件 + // 删除文件(同步) + fs.unlinkSync('./temp.txt'); + + // 删除文件(异步) + fs.unlink('./temp.txt', (err) => { + if (err) throw err; + console.log('删除成功'); + }); +监听变化 +watch / watchFile +练习 +选择题 +下面哪个方法可以检查文件是否存在? + +B. fs.existsSync() + +写入文件使用哪个方法? + +B. fs.writeFileSync() + +appendFileSync和writeFileSync的区别是? + +B. append是追加,write是覆盖 + +如何创建一个多级目录? + +B. fs.mkdirSync('./a/b/c', { recursive: true }) + +下面哪个方法可以获取文件的详细信息(大小、时间等)? + +C. fs.statSync() + +简答题 +请解释同步方法和异步方法的区别。 + +同步会阻塞后续操作,异步不会。 + +fs.readFile和fs.readFileSync有什么区别? + +fs.readFile 是异步方法,‌不会阻塞‌主线程;fs.readFileSync 是同步方法,‌会阻塞‌整个 Node.js 进程直到文件读取完成。 + +什么是流式处理?它适合什么场景? + +流式处理的优势在于能够实现低延迟响应、高效处理大规模实时数据流,并支持弹性伸缩。它特别适用于需要快速决策和响应变化的业务环境。 +如何监听文件的变化? + +可以使用 fs.watch 或 fs.watchFile 方法来监听文件或目录的变化。 +const fs = require('fs'); +const content = fs.readFileSync('./helin.txt', 'utf8'); +console.log(content); +fs.writeFileSync('./helin.txt', 'Hello World'); + + +const fs = require('fs/promises'); +const path = require('path'); + + function copyDirectory(src, dest) { + try { + + await fs.mkdir(dest, { recursive: true }); + + const entries = await fs.readdir(src, { withFileTypes: true }); + + + for (const entry of entries) { + const srcPath = path.join(src, entry.name); + const destPath = path.join(dest, entry.name); + + if (entry.isDirectory()) { + + await copyDirectory(srcPath, destPath); + } else { + + await fs.copyFile(srcPath, destPath); + } + } + + console.log(`目录 "${src}" 已成功复制到 "${dest}"`); + } catch (err) { + console.error('复制目录时出错:', err.message); + } +} \ No newline at end of file diff --git "a/\345\220\264\346\270\212\345\215\232/20260320-nodejs HTTP\346\250\241\346\235\277.md" "b/\345\220\264\346\270\212\345\215\232/20260320-nodejs HTTP\346\250\241\346\235\277.md" new file mode 100644 index 0000000..d3f2722 --- /dev/null +++ "b/\345\220\264\346\270\212\345\215\232/20260320-nodejs HTTP\346\250\241\346\235\277.md" @@ -0,0 +1,109 @@ +## HTTP模块的作用 +- 创建服务器 + - const server = http.createServer((req, res) => {}); +- 发送请求 + // 请求方法 + console.log('方法:', req.method); // GET, POST, PUT, DELETE + + // 请求URL + console.log('URL:', req.url); // /, /about, /api/user + + // 请求头 + console.log('User-Agent:', req.headers['user-agent']); +- 处理请求 +- 返回响应 + // 返回响应 + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('Hello World!'); + +- 选择题 +- 创建一个HTTP服务器需要使用哪个模块? + +B. http + +- 获取请求的方法(GET、POST)应该访问哪个属性? + +B. req.method + +- 设置响应状态码使用哪个属性? + +B. res.statusCode + +- 返回JSON数据需要设置什么响应头? + +B. 'Content-Type': 'application/json' + +- 使用哪个方法发送响应? + +C. res.end() + +- 简答题 +- 请解释req和res分别代表什么? + + - req‌:代表 ‌request(请求)‌。它包含了客户端发送给服务器的所有信息,比如请求的 URL、请求方法(GET、POST 等)、请求头(headers)等。 + + - res‌:代表 ‌response(响应)‌。它是服务器用来向客户端返回信息的对象。你可以通过它设置状态码、添加响应头、发送响应内容等。 + + - http.createServer的回调函数接收哪些参数? + + - req和res + +- 如何获取URL中的查询参数? + + - ‌使用 url 和 querystring 模块(原生 Node.js 方法) + + - 使用 Express 框架 + + - res.writeHead和res.setHeader有什么区别? + + - res.setHeader() 用于设置单个响应头字段。 + + - res.writeHead() 用于发送响应头,并且可以同时设置状态码和多个响应头字段 + + - http.get和http.request有什么区别? + + - http.get 是一个简化的请求方法,专门用于发送 ‌GET‌ 请求。它内部调用了 http.request,并自动设置请求方法为 GET,因此使用更简单。 + + - http.request 是一个更通用的方法,可以用于发送 ‌GET、POST、PUT、DELETE‌ 等各种 HTTP 请求方法。开发者需要手动指定请求方法和其他参数。 + +- 操作题 +```js +const http = require('http'); +const fs = require('fs'); +const path = require('path'); +const server = http.createServer((req, res) => { + + let filePath = '.' + req.url; + if (filePath === './') { + filePath = './index.html'; + } + +const extname = String(path.extname(filePath)).toLowerCase(); + const contentType = mimeTypes[extname] || 'application/octet-stream'; + + fs.readFile(filePath, (error, content) => { + if (error) { + if (error.code === 'ENOENT') { + + fs.readFile('./404.html', (err, content404) => { + res.writeHead(404, { 'Content-Type': 'text/html' }); + res.end(content404, 'utf-8'); + }); + } else { + + res.writeHead(500); + res.end(`Server Error: ${error.code}`); + } + } else { + + res.writeHead(200, { 'Content-Type': contentType }); + res.end(content, 'utf-8'); + } + }); +}); + + +const PORT = process.env.PORT || 3000; +server.listen(PORT, () => { + console.log(`Server running at http://localhost:${PORT}/`); +}); \ No newline at end of file -- Gitee