path模块
path模块是node.js中提供的一个系统模块,用于格式化或凭借一个完整的路径
path模块常用方法:
path.join() 将多个字符串拼接成一个完整的路径
path.dirname() 返回路径中的文件夹部分
path.basename(); 返回路径中的文件部分
path.extname(); 返回路径中的扩展名部分
path.normalize(); 格式路径
path.parse() 解析路径:返回一个对象,包含路径中的各个部分
var path=require("path");
var p1="../../../../path/../a/./b.../c.html"
console.log(path.normalize(p1));//格式化路径
var p2="./day01/hello/zs.html";
console.log(path.join("code",p2));
console.log(path.join(__dirname,p2))
console.log(path.dirname(p2));//返回路径中的文件夹部分
console.log(path.basename(p2));//返回路径中的文件部分(文件名和扩展名)
console.log(path.extname(p2));//返回路径中的扩展名部分
console.log(path.parse(p2));//返回一个对象包含路径中的每一个部分
URL模块
url是全球统一资源定位符,对网站资源的一种简介表达形式,也成为网址;
url的构成:
完整结构:
协议://用户名:密码@主机名.名.域:端口号/目录名/文件名.拓展名?参数名=参数值&参数2=参数值2#hash
http协议的URL常见结构:
协议://主机名.名.域:端口/目录/文件夹.扩展名?参数名=参数值&参数名2=参数值2#hash
https://www.baidu.com:443/img/bd_logo1.png
http://music.163.com:80/#/discover/playlist
node.js的URL模块
在node.js中提供了两套对于URL进行出来的API功能
老的node.js url模块
新的url模块(WHATWG URL标准模块)
//新的url模块
const myURL=new URL('https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash');
//老的url模块
const url = require('url');
const myURL =url.parse('https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash');
url模块获取数据
获取get请求数据
通过get请求发送的数据存储在req.url中,通过let{pathname,query}=url.parse(req.url,true);
可以在query获取到对用的数据
url.parse()方法的第二个参数是布尔值,默认情况下req.url的结果是字符串类型的,通过url.parse
方法的第二参数来决定是否把字符串转为一个对象,为ture时转为对象
//这个模块专门用来搭建服务 供客户端请求以及向客户端响应
const http = require('http');
const fs = require('fs')
//这个模块专门用来处理地址栏的信息
const url = require('url')
var server = http.createServer(function(req,res){
const {pathname,query} = url.parse(req.url,true)
console.log(typeof req.url);
})
server.listen(3003,function(){
console.log('3003端口成功运行')
})
获取post请求数据
post请求:通过post方式发送的数据在请求体中,要获得post数据,可以以流的方式分段读取。获取到的
数据拼接到一个字符串中:req.on("data",chuck=>{str+=chuck}),然后绑定end事件,在结束读取的时候输
出获取到的数据,因为str是一个字符串,可以通过querystring模块的parse方法来转为对象,然后再获取到
对应的属性值
const http = require('http')
//url模块专门处理 https://www.baidu.com :8080/p/a/t/h?query=string#hash
const url = require('url')
const fs = require('fs')
//专门处理user=qweqwe&psd=12312
const qs = require('querystring')
const server = http.createServer(function(req,res){
const {pathname} = url.parse(req.url,true)
if(pathname==='/'){
fs.readFile('./demo.html',function(err,data){
if(err)return
res.end(data)
})
}else if(pathname==='/heaven'){
console.log('表单的数据接受到了')
/*
*前端的post数据存放在请求体中的 并且是分批次传输
* */
var str = ''
req.on('data',function(chunk){
str += chunk
})
req.on('end',function(){
console.log(qs.parse(str));
// console.log('post数据接受完毕')
res.setHeader('content-type','text/html;charset=utf-8')
res.end('数据响应完毕')
})
}else{
res.end('404')
}
})
server.listen(3001,()=>{
console.log('3001端口已经启动了')
})