当前位置: 首页 > news >正文

前端基础知识---10 Node.js(一)

10 正则表达式

限定符:

?表示可以匹配前一个字符出现0次或1次        a?

* 匹配前一个字符出现0次或多次        a* 

+ 匹配前一个字符出现1次或范围次 +{2,6}                (ab)+        可以匹配多个ab

字符类:

[a-z]表示所有的小写字符,[A-Z]表示所有的大写字符       

[a-fA-F0-9]代表所有的大小写字母和数字

[^0-9]匹配非数字字符

元字符:数字\d、空白符\s、单词\w、行首^、结尾$ 等        .任意字符()

贪婪匹配:<.+>

懒惰匹配:<.+?>

10.1 初识Node.js

node.js是一个基于Chrome V8引擎的JavaScript运行环境

JavaScript写在浏览器上是前端开发,写在node.js中就是后端开发。

node是一个独立的运行环境

powershell打开:在文件夹中shift+右键(即可对应到当前文件夹)

10.2 fs模块(读取写入文件)

2.1 fs系统文件模块

示例:

示例:fs整理成绩单

const fs = require('fs')//读取源文件
fs.readFile('./3.成绩单.txt','utf-8',function(err,dataStr){if(err)console.log('文件读取失败:',err)console.log('文件读取成功:',dataStr)//1.将字符串以空格为分隔符分割为字符串
const arrOld = dataStr.split(' ')//2.替换连接方式
const arrNew = []
arrOld.forEach(item =>{arrNew.push(item.replace(':','='))
})//3.将处理好的字符串合并为一个新的字符串,隔行整理
const newArr = arrNew.join('\n')
console.log(newArr)//写入文件
fs.writeFile('./ok.txt',newArr,'utf-8',function(err,dataStr){if(err)console.log('文件写入失败',err)console.log('文件写入成功')
})})

2.2解决路径问题:

__dirname表示当前文件所处目录

10.3 path 使用path模块处理路径

3.1 path.join        (路径操作都要用path.join进行拼接)

../ 抵消掉前面的目录

3.2 path.basename  获取路径中的文件名   

3.3 path.extname         获取路径中的文件拓展名

注意事项:

1. fs.writeFile() 方法只能用来创建文件,不能用来创建路径

2.重复调用 fs.writeFile()写入同一个文件,新写入的内容会覆盖之前的旧内容

10.4 http模块(创建web服务器)

核心原理:HTTP 响应的 “头 - 体” 顺序

HTTP 响应分为「响应头」和「响应体」两部分:

  • 响应头(由 res.setHeader() 或隐式设置)必须先于响应体发送给客户端。
  • 响应体(由 res.write() 或 res.end() 发送)是实际显示的内容。

客户端:消费资源(使用http模块就可以将客户端转为服务器)

服务器:提供资源(区别:安装了web服务器软件

10.4.1服务器相关概念

IP地址:每台计算机的唯一地址;

域名:IP地址和域名是一一对应的关系,这份关系存放在域名服务器(DNS)

域名服务器(DNS):提供IP地址和域名转换服务的服务器

(例如:127.0.0.1和localhost对应)

端口号:(门牌号)  

(1)每个端口号只能对应一个web服务器

(2)在实际应用中,URL中的80端口可以被省略

10.4.2创建基本的web服务器

(1)导入http模块                const http = require('http')

(2)创建web服务器实例               http.createServer()

(3)为服务器实例绑定request事件,监听客户端的请求

(4)启动服务器        .listen()

//1.导入http模块
const http = require('http')
//2.创建web服务器实例
const server = http.createServer()
//3.为服务器实例绑定request事件,监听客户端的请求
server.on('request',function(req,res){console.log('Someone visits our web server')
})
//4.启动服务器
server.listen(8080,function(){      //端口号,回调函数console.log('server running at http://127.0.0.1:8080')
})

10.4.3 req请求对象

在事件处理函数中,访问与客户端相关的数据或属性


//1.导入http模块
const http = require('http')
//2 创建服务器实例
const server = http.createServer()
//3 为服务器实例绑定request事件,监听客户端请求
server.on('request',req =>{const url = req.urlconst method = req.methodconst str = `Your request url is ${url},and request method is ${method}`console.log(str)
})
//4 启动服务器
server.listen(80,()=>{console.log('server running at http://127.0.0.1')
})

10.4.4 res响应对象

  .end() 结束这次的请求

只能响应一次!如果有其他内容要显示在浏览器上可以用 res.write(str2)

10.4.5解决中文乱码问题

 res.setHeader('Content-Type','text/html;charset=utf-8')

10.4.6根据不同的url响应不同的html页面

const http = require('http')
const server = http.createServer()server.on('request',(req,res)=>{//1. 获取客户端请求的url地址const url = req.url//2.设置默认的相应内容let content = '<h1>404 Not found!</h1>'//3.判断用户请求的是什么页面if(url === '/'||url ==='/index.html')content = '<h1>首页</h1>'else if(url === '/about.html')content = '<h1>关于页面</h1>'//4.设置响应头,防止中文乱码res.setHeader('Content-Type','text/html;charset=utf-8')//5.使用res.end()res.end(content)})server.listen(80,()=>{console.log("server running at http://127.0.0.1")
})

案例:实现clock时钟 web服务器

核心思路:把文件的实际存放路径,作为每个资源的请求url地址

注意乱码部分要用映射表

// 1. 导入模块
const http = require('http')
const fs = require('fs')
const path = require('path')// 2.1 创建web服务器
const server = http.createServer()// 2.2 绑定监听事件request
server.on('request', (req, res) => {// 3.1 获取客户端请求的url地址const url = req.url// 3.2 映射URL到具体文件路径let fpath = ''if (url === '/') {fpath = path.join(__dirname, './clock/index.html')} else {fpath = path.join(__dirname, '/clock', url)}// 4. 关键:根据文件后缀名设置正确的Content-Type// 4.1 获取文件扩展名(如 .html、.css、.js、.png)const extname = path.extname(fpath)// 4.2 定义MIME类型映射表(常见文件类型)const mimes = {'.html': 'text/html; charset=utf-8','.css': 'text/css; charset=utf-8','.js': 'application/javascript; charset=utf-8','.png': 'image/png','.jpg': 'image/jpeg','.gif': 'image/gif'}// 4.3 根据扩展名获取对应的MIME类型(默认用text/html)const contentType = mimes[extname] || 'text/html; charset=utf-8'// 4.4 设置响应头(动态类型)res.setHeader('Content-Type', contentType)// 5. 读取文件并响应fs.readFile(fpath, (err, dataStr) => { // 注意:读取非文本文件(如图片)不能加'utf-8'if (err) return res.end("404 Not found.")res.end(dataStr)})
})// 2.3 启动服务器
server.listen(80, () => {console.log('server running at http://127.0.0.1')
})


文章转载自:

http://9wsZiKzr.bfggg.cn
http://kK9C50k0.bfggg.cn
http://VPMwfFIm.bfggg.cn
http://y0qHa9tJ.bfggg.cn
http://0wfbFvde.bfggg.cn
http://CHQxOsXV.bfggg.cn
http://s1f2P6fD.bfggg.cn
http://pFFTdOYH.bfggg.cn
http://MjcetUhF.bfggg.cn
http://Pm8H61Yd.bfggg.cn
http://5F18GTNV.bfggg.cn
http://X9wh1IEU.bfggg.cn
http://U2Ghcx05.bfggg.cn
http://2YrBqUqw.bfggg.cn
http://4i55Q7mj.bfggg.cn
http://T5ecuDc9.bfggg.cn
http://IcBmMu04.bfggg.cn
http://WuyXWCV0.bfggg.cn
http://OkFHFi0i.bfggg.cn
http://GnjP4PLG.bfggg.cn
http://idklXGxy.bfggg.cn
http://JA0wGTe8.bfggg.cn
http://FiDrELVA.bfggg.cn
http://eFFACrAP.bfggg.cn
http://rFsyq8X8.bfggg.cn
http://QnZ5eiJX.bfggg.cn
http://8C72q4qg.bfggg.cn
http://kLIcd1yI.bfggg.cn
http://59V61HUV.bfggg.cn
http://hj2wxbdH.bfggg.cn
http://www.dtcms.com/a/384194.html

相关文章:

  • C语言:求三个整数中的最大值
  • AI 赋能大前端电商应用:智能尺码推荐与搭配建议,重构购物体验
  • 跨境通信合规新解:Z世代多模态交互技术突破
  • SpringBoot返回前端时间格式化处理
  • 高系分四:网络分布式
  • Python 3.9.21 升级到 Python >=3.10
  • 在运维工作中,FTP主动和被动的区别有哪些?
  • CE-Agent 多智能体系统流程图文档
  • 数据结构——逻辑结构物理结构
  • RuoYi-Vue3-FastAPI框架的功能实现(下)
  • PySpark简化数据处理的高效函数有哪些?
  • 哈尔滨云前沿服务器租用托管
  • React项目 新闻发布系统 项目初始化与路由搭建
  • 数字经济专业核心课程解析与职业发展指南
  • Spring Boot 全栈优化:服务器、数据、缓存、日志的场景应用!
  • 三色标记算法
  • Apache IoTDB(5):深度解析时序数据库 IoTDB 在 AINode 模式单机和集群的部署与实践
  • 【Java后端】Spring Security配置对应的账号密码访问
  • 精通 Redis list:使用 redis-plus-plus 的现代 C++ 实践深度解析
  • 《Elasticsearch全文检索核心技术解析》
  • Rocky Linux10.0修改ip地址
  • DevOps实战(7) - 使用Arbess+GitPuk+sourcefare实现Node.js项目自动化部署
  • 学习日报|梳理三类典型缓存问题:缓存穿透、缓存击穿、缓存雪崩
  • 【JavaEE】线程安全-内存可见性、指令全排序
  • MCP传输机制完全指南:Stdio、SSE、Streamable HTTP详解-实践案例-整体对比
  • 基于C#的快递打单系统源码+数据库+使用教程
  • RabbitMQ 高可用实战篇(Mirrored Queue + Cluster + 持久化整合)
  • RabbitMQ 命令执行流程与内核数据结构
  • Dify:Step1 本地化安装部署on MACOS
  • 有鹿机器人:以智能清洁 redefine 服务,以灵活租赁开启可能