route.js
- 为了预防报错,采用try catch
- 采用同步读取文件 ```javascript // 导出函数 exports.xx = function(xx) {xx} const fs = require(“fs”); const http = require(“http”); const path = require(“path”); // 引入自定义函数,直接引入整个文件名 const url = require(“url”);
// 私有方法 let getMime = function (suffix) { return new Promise((resolve, reject) => { // 同步方法 var data = fs.readFileSync(“./data/mime.json”); let mimeObj = JSON.parse(data.toString()); return mimeObj[extname]; // fs.readFile(“./data/mime.json”, (err, data) => { // if (err) { // // console.log(err); // reject(err); // return; // } else { // // data会是buffer字符,所以转成字符串,data.toString() // // 将json解析为JSON.parse,并且赋值给Json // let Json = JSON.parse(data.toString()); // // Json后缀名是通过数组的形式呈现的,所以用Json[xx]; // // console.log(Json[suffix]); // resolve(Json[suffix]); // } // }); }); };
// 文件放在static文件夹里面,就可以实现文件自动读取和下载 // 外部读取时,采用文件名.static来使用该函数 exports.static = function (req, res, staticPath) { let pathname = url.parse(req.url).pathname; // console.log(pathname); pathname = pathname == “/“ ? “/index.html” : pathname;
// 获取后缀名 let extname = path.extname(pathname); // 2.通过fs模块读取文件 if (pathname != “/favicon.ico”) { // 使用fs读取文件,路径+文件名,还有处理函数 // 通过读取文件,来实现对服务器静态资源的访问 // if (err) { // // err里面也包含头文件和end // res.writeHead(404, { “Content-Type”: ‘text/html ;charset=”utf-8”‘ });
// res.end("404 文件不存在");// }// if (!err) {// let mime = await getMime(extname);// res.writeHead(200, {// "Content-Type": "" + mime + ' ;charset="utf-8"',// });// res.end(data);// }//为了预防报错,采用try catchtry {// 采用同步读取文件let data = fs.readFileSync("./" + staticPath + pathname);if (data) {let mime = getMime(extname);res.writeHead(200, {"Content-Type": "" + mime + ' ;charset="utf-8"',});res.end(data);}} catch (error) {}// 需要使用第三方的函数时,使用文件名.函数()
} };
**app.js**1. 创建静态web服务1. 路由1. 需要配置头文件**代码**```javascriptconst http = require("http");const fs = require("fs");const path = require("path");// 引入自定义函数,直接引入整个文件名const route = require("./module/route");const url = require('url');http// req是一个对象,包含有关引发事件的 HTTP 请求的信息。响应req,您使用res发送回所需的 HTTP 响应。.createServer(function (req, res) {//创建静态web服务route.static(req, res, "static");// 路由let pathname = url.parse(req.url).pathname;if(pathname == '/login') {// 需要配置头文件res.writeHead(200, {"Content-Type": 'text/html;charset="utf-8"',});res.end('处理登录');}else if(pathname == '/register') {res.writeHead(200, {"Content-Type": 'text/html;charset="utf-8"',});res.end('处理注册');}else if(pathname == '/order') {res.writeHead(200, {"Content-Type": 'text/html;charset="utf-8"',});res.end('处理预定');}else {res.writeHead(404, {"Content-Type": 'text/html;charset="utf-8"',});res.end('页面不存在');}}).listen(4000);console.log("server running at http://127.0.0.1:4000/");
