一.使用node搭建服務(wù)器
—內(nèi)置模式:http,fs,url,querystring
-(1)http? 服務(wù)器
//?引入服務(wù)器模塊
const?http?=?require("http");
//?創(chuàng)建一個(gè)服務(wù)器對象
const?serverObj?=?http.createServer((req,res)=>{
????//?服務(wù)器被訪問后要執(zhí)行的代碼
????//?req:請求頭對象(前端到后端的信息對象)
????//?res:響應(yīng)頭對象(后端到前端的信息對象)
????if(req.url?!==?"/favicon.ico"){
????????//?路由處理
????????if(req.url?===?"/"){
????????????res.write("home");????//?前后端交互只能交互字符
????????}else?if(req.url?===?"/index.html"){
????????????res.write("index");
????????}else?if(req.url?===?"/page.html"){
????????????res.write("page");
????????}else{
????????????res.write("404");
????????}
????????res.end();
????}
})
//?開啟監(jiān)聽,監(jiān)聽端口
serverObj.listen("10086");
//?開啟監(jiān)聽地熄,監(jiān)聽端口和地址
//?serverObj.listen("10086","127.0.0.2");
//?開啟監(jiān)聽,監(jiān)聽端口和地址成功后執(zhí)行回調(diào)函數(shù)
//?serverObj.listen("10086","127.0.0.2",()=>{
//?????console.log("服務(wù)器開啟成功:http://127.0.0.2:10086")
//?});
-(2)fs 文件系統(tǒng)
const?fs?=?require("fs");
//?console.log(fs)
//?異步的讀
//?fs.readFile(地址,編碼,回調(diào)函數(shù))
//?fs.readFile('./public/text.txt',編碼,回調(diào)函數(shù))
//?fs.readFile('./public/text.txt',"utf-8",(err,data)=>{
//?????if(err){
//?????????console.log(404)
//?????}else{
//?????????console.log(data)
//?????}
//?})
//?同步的讀
const?data?=?fs.readFileSync('./public/text.txt');
console.log(data);
//?異步的寫
//?fs.writeFile("./public/data.txt","寫入的數(shù)據(jù)",(err)=>{
//?????if(!err){
//?????????console.log("寫入成功")
//?????}
//?})
//?同步的寫
//?fs.writeFileSync("./public/data.txt","1321221");
3.url模塊
4.querystring模塊