**引入模块**
const http=require("http");
const fs=require(fs"");
const path=require("path");
**创建服务器**
var ser=http.createServer((req,res)=>{//创建本地服务器
//req请求对象;res响应对象;
if(req.url==="/favicon.ico")return ;//处理请求图标报错;
req.url=req.url="/"? /index.html:req.url;//处理"/"请求;
url=path.join(__dirname,req.url);//将请求地处理为绝对经;
res.writeHead(200,{"content-type":"text/html;charset=utf-8"});
//写服务器头部;200服务器请求成功;内容为text/html文件,字符格式为中文;
fs.stat(url,(err,info)=>{//读取当前文件的状态
if(!err){//读取文件成功
fs.createReadStream(url).pipe(res);
//根据url读取到指定文件,并将文件流导向res;
}else{
res.end("请求文件不存在!");
}
})
//res.write("你好,这是自己搭建大服务器!");
//res.end("服务器请求结束!");
})
**监听端口**
ser.listen(3000,()=>{//listen为http接口的监听方法;
//第一个参数为端口号;第二个参数为回调函数;当该端口被触发时执行回调函数;
console.log("监听服务器请求接口!");
})
node.js搭建本地服务器
最新推荐文章于 2024-07-18 10:57:59 发布