node.js的http模块创建基本Web服务器

 1 首先下载node.js模块.终端执行命令
 2 npm i node -g
 3 引入http核心模块
 4 const http =require('http')
 5 引入文件系统模块
 6 const fs =require('fs')
 7 引入文件绝对路径模块
 8 const path =require('path')
 9 创建服务器对象
10 const server =http.createServer()
11 为server服务器对象绑定处理函数
12 server.on('request',(req,res)=>{
13     定义请求地址
14     let url =req.url
15    判断请求url地址,返回对应的html内容 
16     if(url==='/') url='/views/index.html'
17     fs.readFile(path.join(__dirname,url),(err,buf)=>{
18     if(err) return res.end('404,Not found')
19       res.end(buf)  
20    })    
21 })
22 监听启动服务器
23 server.listen(3000,()=>{
24     console.log(http://127.0.0.1:3000)
25 })

 

posted @ 2019-01-02 18:51  你的张二狗  阅读(362)  评论(0编辑  收藏  举报