接下来使用以上学过的url
,http
,fs
等模块,创建一个静态web服务器。
web服务器一般指网站服务器,是指驻留于因特网撒花姑娘某种类型计算机的程序,可以向浏览器等web客户端提供文档,也可以放置往回走哪文件让全世界浏览,还可以放置数据文件,让全世界下载。目前最主流的web服务器有Apache、Nginx
、lls
等。
Nodejs
创建一个web服务器
app.js
const http = require('http');
const fs = require('fs');
const common=require('./module/common.js');
const path=require('path');
const url=require('url');
http.createServer(function (req, res) {
//1.获取请求地址;
var pathname = url.parse(req.url).pathname;
//1.1 当初始请求是根目录/
pathname = pathname == '/' ? '/index.html' : pathname;
//获取后缀名paht.exthname()
let extname=path.extname(pathname);
//2.通过fs模块读取文件
if (pathname != '/favicon.ico') {
//刚开始我在服务器的最外层写了一行响应语句 res.end("hello world"),导致每次都访问不到文件,就几行代码找了半天,后来把它删了才正确访问到了。原因其实很简单,
//因为readFile是一个异步执行,所以在等程序还没有读文件完毕的时候,下面这行代码直接把响应关闭了。
fs.readFile('./static' + pathname, async(err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
res.end("这个页面不存在");
}
let mime=await common.getFileMime(extname);
//返回成功响应头
res.writeHead(200, { 'Content-Type': ''+mime+';charset="utf-8"' });
//返回查询到的数据
res.end(data);
})
}
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
common.js
var fs=require('fs');
exports.getMime=function(extname){
switch(extname){
case '.html':
return 'text/html';
case '.css':
return 'text/css';
case '.js':
return 'text/javascript';
default:
return 'text/html';
}
}
exports.getFileMime=function(extname){
//因为fs.readeFile是异步操作,所以将其放在promise当中
return new Promise((resolve,rejects)=>{
//这里的mime.json文件中存放的是后缀名和类型匹配的内容
fs.readFile('./data/mime.json',(err,data)=>{
if(err){
rejects(arr);
return ;
}
let mimeobj=JSON.parse(data.toString());
resolve(mimeobj[extname]);
})
})
}
static/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div id="main">我是index.html</div>
</body>
</html>