const url = require("url");
const fs = require("fs");
const path = require("path");
let G = {
_get: {},
_post: {},
static: "static",
};
const changeRes = (res) => {
res.send = (data) => {
res.writeHead(200, { "Content-type": "text/plain;charset=utf-8" });
res.end(JSON.stringify(data));
};
};
const initStatic = (res, pathname) => {
try {
const extname = path.extname(pathname);
let type;
try {
const jsonData = JSON.parse(fs.readFileSync("./mime.json"));
type = jsonData[extname];
} catch (err) {
}
let data = fs.readFileSync("./" + G.static + pathname);
res.writeHead(200, { "Content-type": `${type};charset=utf-8` });
res.end(data);
} catch (err) {}
};
const app = (req, res) => {
const pathname =
url.parse(req.url).pathname == "/"
? "/index.html"
: url.parse(req.url).pathname;
changeRes(res);
initStatic(res, pathname);
if (req.method === "GET") {
if (G._get[pathname]) {
G._get[pathname](req, res);
}
} else {
if (G._post[pathname]) {
let data = "";
req.on("data", (chunk) => {
data += chunk;
});
req.on("end", () => {
req.body = data;
G._post[pathname](req, res);
});
}
}
};
app.get = (pathname, cb) => {
G._get[pathname] = cb;
};
app.post = (pathname, cb) => {
G._post[pathname] = cb;
};
app.static = (path) => {
G.static = path;
};
module.exports = app;
使用
const http = require("http");
const app = require("./express");
const qs = require("querystring");
const { MongoClient } = require("mongodb");
http.createServer(app).listen(8080);
app.get("/test", (req, res) => {
MongoClient.connect("mongodb://127.0.0.1:27017/", (err, client) => {
if (err) {
res.send({ code: 200, msg: err });
return;
}
const db = client.db("itying");
const order_collection = db.collection("order");
order_collection
.aggregate([
{
$lookup: {
from: "order",
localField: "order_id",
foreignField: "order_id",
as: "items",
},
},
])
.toArray((err, data) => {
if (err) {
res.send({ code: 200, msg: err });
client.close();
return;
}
res.send({ code: 200, msg: "", data });
client.close();
return;
});
});
});
app.post("/register", (req, res) => {
res.send(qs.parse(req.body));
});
app.static("public");