Node的使用过程中需要很多核心模块的引入:
const http = require("http");
const {URL} = require("url");
const fs = require('fs');
const path = require('path');
有了这些模块,能更好的让我们体验Node的使用。模块中的操作包括了异步操作和同步操作
fs模块
1.读取文件
//异步
fs.readFile("./yes.txt","utf8",function(err,data){
if(err){ //回调函数是实现异步的基本操作
console.log("文件读取失败,原因是" + err);
return;
}
console.log(data);
})
//同步
const data = fs.readFileSync("./yes.txt","utf8");
console.log(data);
console.log("Number:"); //打印结果与上边程序结果相反,因为前边代码不完成,后边无法执行。
2.写文件,会把原文件内容覆盖掉
//异步
var text = "four"
fs.writeFile("./yes.txt",text,function(err){
if(err){
console.log("文件写入失败,原因是" + error);
return;
}
console.log("文件写入成功");
})
//同步
var text = "123456"
fs.writeFile("./ok.txt",text,function(err){ //如果没有就会生成,只能同级操作
if(err){
console.log("文件写入失败,原因是" + error);
return;
}
console.log("文件写入成功");
})
3.追加内容,在文档后直接加上新内容
//追加内容
var text = " four"
fs.appendFile("./yes.txt",text,function(err){
if(err){
console.log("文件追加失败,原因是" + error);
return;
}
console.log("文件追加成功");
})
4.拷贝操作,把ok的内容拷贝进yes 会覆盖原内容
//拷贝内容
var text = "123456"
fs.copyFile("./ok.txt","./yes.txt",function(err){ //如果没有就会生成,只能同级操作
if(err){
console.log("文件拷贝失败,原因是" + error);
return;
}
console.log("文件拷贝成功");
})
对大文件进行流操作
1.读取流
//流操作
const rs = fs.createReadStream("./ohyes.txt",{encoding:"utf-8"});
rs.on("open",function(){
console.log("读取流打开");
})
let text = '';
rs.on("data",function(chunk){ //chunk是一个buffer,是当前读取的数据片段,本质是一个二进制数据流
text += chunk;
// console.log(count);
})
rs.on("end",function(){
console.log("文件读取完成");
console.log(text);
})
rs.on("close",function(){
console.log("读取流关闭");
})
2.写入流
//写入流
const ws = fs.createWriteStream("./ok.txt");
ws.write("66666");
ws.end();
ws.on("open",function(){
console.log("写入流开启");
})
ws.on("close",function(){
console.log("写入流关闭");
})
执行路径会影响结果,不建议使用相对路径,建议使用绝对路径
path模块
path方法:
basename():文件名+后缀
dirname() :路径名
extname():后缀名
join():拼接路径
parse():将路径解析成对象
format():将对象整合成路径字符串
isAbsolute():是否是一个绝对路径(返回布尔值)
let p = "C://Users/DELL/Desktop/10_Node/node-1.html"
console.log(path.basename(p));//文件名+后缀
console.log(path.dirname(p));//路径名
console.log(path.extname(p));//后缀名
console.log(path.join("/a","/b/c","../d"));//拼接路径 不同于字符串拼接,可以对内容(../)进行转义
console.log("/a"+"/b/c"+"../d");
console.log(path.parse(p));//将路径解析成对象
console.log(path.format(
{
root: 'C:/',
dir: 'C://Users/DELL/Desktop/10_Node',
base: 'node-1.html',
ext: '.html',
name: 'node-1'
}
));//将对象整合成路径字符串
console.log(path.isAbsolute(p));//是否是一个绝对路径
url模块
const {URL} = require("url")
const url = newURL("http://localhost:8080/index.html?a=1&b=2");
结果:
URL {
href: 'http://192.168.0.3:3000/soul/users/hb/sjz/xh.json?sex=1&age=[18,26]',
origin: 'http://192.168.0.3:3000',
protocol: 'http:',
username: '',
password: '',
host: '192.168.0.3:3000',
hostname: '192.168.0.3',
port: '3000',
pathname: '/soul/users/hb/sjz/xh.json',
search: '?sex=1&age=[18,26]',
searchParams: URLSearchParams { 'sex' => '1', 'age' => '[18,26]' },
hash: ''
}
http模块
IP地址
每一台计算机在互联网的地址唯一,使用点分十进制表示,在终端可以使用 ping + 网址查看IP,127.0.0.1是计算机的本地地址(localhost)。
域名&端口号
域名具有唯一性。一台计算机可以开启多个web服务,但是每个web服务对应唯一的端口,80端口是默认的,可省略不写。
http模块的使用
const http = require('http'); //引入核心模块 http
const fs = require('fs');
//createServer() 创建服务
//listen(port) 监听端口并开启服务
//req:请求体
//res:响应体
const server = http.createServer((req,res) =>{ //req:前端给的信息 res:给前端的信息
if(req.url === '/myapp/index.html' || req.url === '/'){
// __dirname:当前文件所在文件夹的绝对路径
fs.readFile(__dirname + '/myapp/index.html',(err,data)=>{
if(err) throw err;
res.end(data); //向前端返回内容
});
}else{
res.end('');
}
})
server.listen(8080,()=>{ //监听成功就服务启动
("http server is running on port 8080");
}); //监听端口号
在终端输入“node + 文件名.js”,待打印"http server is running on port 8080"之后,即可在网页运行。