fs模块
1.读取文件
(1)异步读取fs.readFile
fs.readFile使用方法是通过异步的方式将要读取的文件内容读入缓存区,再从缓存区中读取文件内容,且没有返回值。
fs.readFile("./avatar2/a.txt","utf-8",(err,data)=>{
if(!err){
console.log(data)
}
})//读取当前文件夹下的avatar2文件夹下的a.txt文件内容以“utf-8”的格式打印在控制台。
该方法有三个参数:path、options、callback。
path:表示文件名或者文件路径。
options:指定字符编码格式。
callback:表示一个回调函数,会传入两个参数(err,data),其中data是文件的内容,err是错误的信息,没有则为空。
(2)同步读取fs.readFileSync
fs.readFileSync和fs.readFile基本一致,不过fs.readFileSync使用的是同步的方式读取数据,且读取的内容通过返回值获取。
2.写文件
(1)异步写入fs.writeFile
fs.writeFile("./avatar2/a.txt","hello",err=>{
console.log(err);
})//会覆盖已经有的
参数包括文件路径,写入的内容和回调函数。
(2)同步写入fs.writeFileSync
fs.writeFileSync和fs.writeFile基本一致,不过fs.writeFileSync是使用同步的方式写入数据。
(3)追加写入fs.appendFile
fs.writeFile方法写入数据时会覆盖文件中的已有数据,当要在文件中追加写入数据即保存原有数据时可使用fs.appendFile方法。
fs.appendFile("./avatar2/a.txt","\nhello world",err=>{
console.log(err);
})//向文件中追加“\nhello world”
3.目录操作
(1)创建和删除目录(文件夹)
1.创建语法:
fs.mkdir("./avatar",(err)=>{
if(err&&err.code=="EEXIST"){
console.log("目录已经存在");
}
})//在当前文件夹下创建avatar文件夹
fs.mkdir方法参数包括:要创建的目录名,回调函数
2.删除语法:
fs.rmdir("./avatar2",err=>{
if(err&&err.code==="ENOENT"){
console.log("目录不存在");
}
console.log(err);
})
删除文件夹时应使用unlink方法删除文件夹内部的文件。
fs.readdir("./avatar2",(err,data)=>{
data.forEach(item=>{
fs.stat(`./avatar2/${item}`,(err,file)=>{
if(file.isFile()){
fs.unlink(`./avatar2/${item}`,err=>{
console.log(err);
})//stat方法读取文件状态,如果文件类型是File则用unlink方法删除
}
else{
fs.rmdir(`./avatar2/${item}`,err=>{
console.log(err);
})//如果类型是文件夹则用rmdir方法删除
}
})
})
})
url模块
new URL(urlString,base),如果urlString是相对路径则需要base。如果是绝对路径则忽略base。其部分属性如下:
- hostname:获取及设置URL的主机名部分,它和host的区别是它不包含端口号部分。
- pathname:获取及设置URL路径部分,也就是端口号后面的所有内容
- search:获取及设置URL的序列化查询部分。即?后面的所有内容,包括?。
//地址:localhost:3000/home?a=10
const myURL = new URL(req.url, 'http://127.0.0.1:3000/')
console.log(myURL.hash);//
console.log(myURL.host);//127.0.0.1:3000
console.log(myURL.hostname);//127.0.0.1
console.log(myURL.pathname);///home
console.log(myURL.search);//?a=10
在http请求中,可以使用new URL()来获取需要的数据:
- 第一个参数相对于req.url
- 第二个参数相对于req.headers.host
url.parse()
语法:var urlobj=url.parse(req.url,true)
输出结果:
//req,url:localhost:3000/home?a=10
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?a=10',
query: [Object: null prototype] { a: '10' },
pathname: '/home',
path: '/home?a=10',
href: '/home?a=10'
}
url.format() 方法将传入的url对象,拼接成url路径字符串:
var params = {
protocol: "https:",
hostname: "www.baidu.com",
port: "8080",
pathname: "/a",
search: "?name=zhangsan&age=20",
}
console.log(url.format(params));
//https://www.baidu.com:8080/a?name=zhangsan&age=20
url.resolve(from,to)
拼接url路径,按照第一个参数的目录路径来拼接,
console.log(url.resolve('/one/two/three/', 'four'));///one/two/three/four
console.log(url.resolve('http://one.com/two/three/', '../four'));//http://one.com/two/four
如果第一个参数中有域名则替换域名后面第一个“/”后的内容,如果第二参数出现.这个向上返回一级后拼接,两个.则返回两级再拼接