一、同步&异步
所有的方法都有同步和异步的形式
node里关于文档的操作方法基本都给了2份,即同步与异步
使用前需要导入核心模块(核心模块:下载node.js时自带的)
二、fs——文件操作
1、读文件 fs.readFile() 异步操作
fs.readFile("所要读的文件","utf8"function(err,data){
if(err) throw err;
console.log(data);
})
fs.readFileSync() 同步操作
const data = fs.readFileSync("所要读的文件","utf8")
console.log(data)
2、写文件 fs.writeFile()
fs.writeFile("要写入的文件","写入的内容",function(err){
if(err) throw err;
})
效果:会删掉文档原来的内容,写入新的内容,如果指定的文档不存在,则新建
其中新建的文档必须为同级
3、追加 fs.appendFile()
fs.appendFile("./yes.txt","./no.txt",function(err){
if(err) throw err;
}) yes的后面追加no的内容
4、拷贝 fs.copyFile()
fs.copyFile("./yes.txt","./no.txt",function(err){
if(err) throw err;
}) yes的内容copy到no
三、fs——流操作
一般读取的时大文件
1、读取流
const fs = require("fs"); //引入核心模块
const rs = fs.createReadStream("读取的文档",{encoding:"utf8"});
rs.on("open",function(){
console,log("可读流开启");
})
rs.on("data",(chunk) => {
console.log(chunk); //chunk时一个Buffer,当前读取的数据片段,二进制数据流
})
rs.on("end",() => {
console,log("可读流读取结束");
})
rs.on("close",() => {
console,log("可读流guanbi");
})
2、写入流
const fs = require("fs"); //引入核心模块
const ws = fs.createWriteStream("写入的文档");
ws.write("写入的内容");
ws.end();
ws.on("open",function(){
console,log("可写流开启");
})
ws.on("close",function(){
console,log("可写流关闭");
})
四、path
basename() 文件名+后缀
dirname() 路径名
extname() 后缀名
join() 拼接路径
parse() 将路径解析成对象
format() 将对象整合成路径字符串
isAbsolute() 是否是一个绝对路径
五、http
完整的URL路径:协议+IP/域名+端口号+路由+?+参数信息
第一个http服务
var http = require("http"); //引入核心模块
http.creatServer((req,res) => {
res.writeHead(200,{"content-type":"text/html;charset=utf-8"}); //一定要写响应头
res.end(); //向前端返回内容
}).listen(port); //监听端口并开启服务
六、url
const {URL} = require("url") //引入核心模块
const url = new URL("http://localhost:8080/index.html?a=1&b=2") //必须是完整的url