node.js中fs和http模块搭建服务

学习了通过node.js搭建服务,渲染页面,让我意识到,这些是为了让我们逐渐脱离phpstudy集成环境,能够做到自己搭建服务器;所以要如何做呢
第一步:当然是引入模块

const http =  require('http');
const fs =  require('fs');
const url =  require('url');

这三个模块是我们接下来要用到的;

第二部:搭建服务

const server = http.createServer((req,res)=>{//req,res参数的用法在之前章节讲过
    const myPath = url.parse(req.url).pathname;//利用url模块获得路径名
    if(myPath ==='/favicon.ico'){//站标获取
        fs.readFile('./favicon.ico',(err,data)=>{//Es6箭头函数
            if(!err) res.end(data)//如果没有错误的话正常结束响应
            else res.end("404");//有错误就报404
        })
    }else if(myPath ==='/my'){//主页获取
        fs.readFile('./index.html',(err,data)=>{
            if(!err) res.end(data);
            else res.end('404')
        })
    }else if(myPath ==='/index.css'){//css文件获取
        fs.readFile('./index.css',(err,data)=>{
            if(!err) res.end(data);
            else res.end('404');
        })
    }
})

第三步:设置端口号

server.listen(80,()=>{//80默认http端口
    console.log('搭建成功')
})

执行结果

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章