简单服务器的创建(2)

该系列随笔为本人巩固知识所写,不足之处还请指出
//
引入http模块 const http = require('http'); //引入url模块 const url = require('url'); //创建名为app的服务器 const app = http.createServer(); //引入路径模块 const path = require('path'); //引入fs模块 const fs = require('fs'); // 引入第三方模块mime(需要先用npm下载) const mime = require('mime'); // 服务器接受请求 app.on('request', (req, res)=> { //将路径通过url.parse()方法得到,该方法的说明上文已提到 let {pathname, query} = url.parse(req.url, true); // 如果路径是空的,就让他等于主页的地址,反之不变 pathname = pathname == '/' ? '/default.html' : pathname; // 用拼接的方式得到文件在服务器端硬盘的绝对位置 let filepath = path.join(__dirname , 'public' + pathname); // 通过mime.getType()方法可以把filepath位置的html文件中所需的所有文件的格式得到 let type = mime.getType(filepath); //打开文件操作 fs.readFile( filepath, (err, result) => { // 如果有错就退出 if( err != null) { res.end('fault'); return; } // 设置资源的类型 res.writeHead(200, { 'content-type' : type }) // 返回得到的页面 res.end(result); }) }) // 链接端口 app.listen(3000); //是否成功打开的判断 console.log('创建服务器成功');

 

posted @ 2020-05-13 21:17  Dokom  阅读(128)  评论(0编辑  收藏  举报