目录
背景
补充学习下node知识,课程来自黑马
npm、包、模块化、身份认证、CORS 跨域
MySQL 数据库、API 接口项目开发
nodejs学习路径
js-node.js内置API(fs、path、http)+第三方API模块(express、mysql)
个人学习笔记,如有侵权,会删除。
黑马的课程真的太赞了!!!
因为大部分是截图,所以这个系列笔记不做了,或者直接隐藏了。大家感兴趣的可以直接b站搜索黑马nodejs课程
笔记
1.node 是什么
- js可以在浏览器运行,是因为浏览器里面有引擎(不同的引擎使用不同的js解析引擎)
- js可以操控DOM和BOM,是因为浏览器自带DOM,BOM,Ajax这些内置web API,js代码调用后,然后被浏览器引擎解析和执行
- js 运行环境,chrome为例(v8 引擎,内置API,待执行js代码)
- js如何做后端开发,使用nodejs.使用浏览器就可以做前端开发
Nodejs是一个基于V8引擎的js运行环境 - nodejs内置api
- 可以做啥
2.fs
操作文件的模块
fs读取
3. demo
1-fs-read.js
```
const fs=require('fs')
fs.readFile('./1.txt','utf8',function(err,dataStr){
//如果读取成功,则err值为null
//如果读取失败,则err值为错误对象,datastr值为undefined
// console.log(err)
// console.log('--------')
// console.log(dataStr)
if(err){
console.log("error!"+err.message)
}else{
console.log('success!'+dataStr)
}
})
```
1.txt
1111
fs写入
demo
2-fs-input.js
const fs=require('fs')
fs.writeFile('./2.txt','abcd',function(err){
//成功,err为null
//失败,err为错误对象(./s/2.txt,路径错误)
//console.log(err)
if(err){
console.log('err'+err.message)
}
console.log("work well")
})
fs Eg:整理成绩
3-score.txt
小红=99 小白=100 小黄=70 小黑=66 小绿=88
3-fs-score.js
const fs=require('fs')
fs.readFile('./3-score.txt','utf8',function(err,score){
if(err){
console.log('error! '+err.message)
}
//成绩,按照空格进行分割,变成数组
const data=score.split(' ')
//分隔后的数组每一个数据,进行字符串替换
const newdata=[]
data.forEach(item=>{
newdata.push(item.replace('=',':'))
})
//把新数组每一项,通过join换行合并,得到新数组
const newStr=newdata.join('\n\r')
console.log(newStr)
fs.writeFile('./3-new-score.txt',newStr,function(err){
if(err){
console.log(err.message)
}
console.log('work well')
})
})
fs 处理路径
路径动态拼接问题
解决方案1:使用绝对路径。缺点:容易写错,不便于迁移,和维护
解决方案2: 使用__dirname,获取当前文件所在目录
const fs=require('fs')
console.log(__dirname)
fs.readFile(__dirname+'/1.txt','utf8',function(err,dataStr){
if(err){
console.log("error!"+err.message)
}else{
console.log('success!'+dataStr)
}
})
3.path
path.join/basename()
+号容易出问题
const path=require('path')
const fs=require('fs')
//../会抵消前面的路径
const test1=path.join('/a','/b/c','../../','./d','e')
console.log(test1);
//可以忽略些小错误,比如./1.txt里面这个.
//如果是+,就会报错 xxx./1.txt
fs.readFile(path.join(__dirname,'/1.txt'),'utf8',function(err,dataStr){
if(err){
console.log("error!"+err.message)
}else{
console.log('success!'+dataStr)
}
})
const path=require('path')
const fpath='/a/b/c/index.html'
const namewitoutExt=path.basename(fpath,'.html')
console.log(namewitoutExt)
path.extname()
Eg:时钟
把一个js文件,拆分成三个小文件,clock底下:js,html,css文件
const fs=require('fs')
const path=require('path')
//匹配<style></style> 标签的正则
//匹配 \s 表示空白字符;\S 表示非空白字符;*表示匹配任意次
//<\/style>,\转义/
const regStyle = /<style>[\s\S]*<\/style>/
const regScript = /<script>[\s\S]*<\/script>/
fs.readFile(path.join(__dirname,'./index.html'),'utf8',function(err,dataStr){
if(err){
console.log('error'+err.message)
}
//读取成功,调用方法,拆分css,js,html文件
resolveCss(dataStr)
resolveJs(dataStr)
resolveHTML(dataStr)
})
//处理css样式的办法
function resolveCss(htmlStr){
//通过正则提取出html里面我们所需要的内容,展示为数组
const r1=regStyle.exec(htmlStr)
//把style替换掉
const newCSS=r1[0].replace('<style>','').replace('</style>','')
fs.writeFile(path.join(__dirname,'./clock/index.css'),newCSS,function(err,dataStr){
if(err){
console.log('err'+err.message)
}
console.log('css ok')
})
}
function resolveJs(htmlStr){
//通过正则提取出html里面我们所需要的内容,展示为数组
const r1=regScript.exec(htmlStr)
//把style替换掉
const newJs=r1[0].replace('<script>','').replace('</script>','')
fs.writeFile(path.join(__dirname,'./clock/index.js'),newJs,function(err,dataStr){
if(err){
console.log('err'+err.message)
}
console.log('js ok')
})
}
function resolveHTML(htmlStr){
//使用replace方法,把内联的<style><script>换成外联<link><script>
const newHtml=htmlStr
.replace(
regStyle,'<link rel="stylesheet" href="./index.css"/>')
.replace(
regScript,'<script src="./index.js"></script>'
)
fs.writeFile(path.join(__dirname,'./clock/index.html'),newHtml,function(err,dataStr){
if(err){
console.log('err'+err.message)
}
console.log('html ok')
})
}
html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>index首页</title>
<style>
html,
body {
margin: 0;
padding: 0;
height: 100%;
background-image: linear-gradient(to bottom right, red, gold);
}
.box {
width: 400px;
height: 250px;
background-color: rgba(255, 255, 255, 0.6);
border-radius: 6px;
position: absolute;
left: 50%;
top: 40%;
transform: translate(-50%, -50%);
box-shadow: 1px 1px 10px #fff;
text-shadow: 0px 1px 30px white;
display: flex;
justify-content: space-around;
align-items: center;
font-size: 70px;
user-select: none;
padding: 0 20px;
/* 盒子投影 */
-webkit-box-reflect: below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0%, transparent), to(rgba(250, 250, 250, .2)));
}
</style>
</head>
<body>
<div class="box">
<div id="HH">00</div>
<div>:</div>
<div id="mm">00</div>
<div>:</div>
<div id="ss">00</div>
</div>
<script>
window.onload = function () {
// 定时器,每隔 1 秒执行 1 次
setInterval(() => {
var dt = new Date()
var HH = dt.getHours()
var mm = dt.getMinutes()
var ss = dt.getSeconds()
// 为页面上的元素赋值
document.querySelector('#HH').innerHTML = padZero(HH)
document.querySelector('#mm').innerHTML = padZero(mm)
document.querySelector('#ss').innerHTML = padZero(ss)
}, 1000)
}
// 补零函数
function padZero(n) {
return n > 9 ? n : '0' + n
}
</script>
</body>
</html>
需要注意的点
4. http
http模块
http作用
服务器概念
IP地址
域名
端口号
创建web 服务器
const http=require('http')
const server=http.createServer()
server.on('request',function(req,res){
console.log('Someone visit our web server.')
})
server.listen(80,function(){
console.log('server running at http://127.0.0.1:80')
})
req
const http=require('http')
const server=http.createServer()
//req是请求对象,包含了与客户端相关的数据和属性
server.on('request',(req)=>{
//客户端请求的url地址
const url=req.url
//客户端请求的method类型
const method=req.method
const str= `${url},${method}`
console.log(str)
})
server.listen(80,()=>{
console.log('server running at http://127.0.0.1:80')
})
res
const http=require('http')
const server=http.createServer()
//req是请求对象,包含了与客户端相关的数据和属性
server.on('request',(req,res)=>{
//客户端请求的url地址
const url=req.url
//客户端请求的method类型
const method=req.method
const str= `${url},${method}`
console.log(str)
//调用res.end方法,响应客户端一些内容
//向客户端发送指定的内容,并结束这次请求的处理内容
res.end(str)
})
server.listen(80,()=>{
console.log('server running at http://127.0.0.1:80')
})
中文乱码
const http=require('http')
const server=http.createServer()
//req是请求对象,包含了与客户端相关的数据和属性
server.on('request',(req,res)=>{
//定义一个中文字符串
const str=`今年是2022年 ${req.url} ${req.method}`
//解决中文乱码,设置响应头Content-Type值为text/html;charset=utf-8
res.setHeader('Content-Type','text/html;charset=utf-8')
//调用res.end方法,响应客户端一些内容
//向客户端发送指定的内容,并结束这次请求的处理内容
res.end(str)
})
server.listen(80,()=>{
console.log('server running at http://127.0.0.1:80')
})
Eg:不同url响应不同的html
const http=require('http')
const server=http.createServer()
//req是请求对象,包含了与客户端相关的数据和属性
server.on('request',(req,res)=>{
// 1. 获取请求的 url 地址
const url = req.url
// 2. 设置默认的响应内容为 404 Not found
let content = '<h1>404 Not found!</h1>'
// 3. 判断用户请求的是否为 / 或 /index.html 首页
if(url==='/'|| url==='/index.html'){
content='<div>这是首页</div>'
}
// 4. 判断用户请求的是否为 /about.html 关于页面
else if(url==='/about.html'){
content='<div>这是关于界面</div>'
}
res.setHeader('Content-Type','text/html;charset=utf-8')
res.end(content)
})
server.listen(80,()=>{
console.log('server running at http://127.0.0.1:80')
})
Eg:web服务器
原理
const http=require('http')
const fs=require('fs')
const path=require('path')
const server=http.createServer()
server.on('request',function(req,res){
const url=req.url
let fpath=''
if(url==='/'){
fpath=path.join(__dirname,'./clock/index.html')
}else{
fpath=path.join(__dirname,'./clock/',url)
}
fs.readFile(fpath,'utf8',(err,dataStr)=>{
if(err){
res.end('404 not found.')
}
res.end(dataStr)
})
})
server.listen(80,function(){
console.log('http://127.0.0.1:80')
})