前端基础知识---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')
})