From 0071cf19500d626f26c9d89b755c6a9050c0f4d6 Mon Sep 17 00:00:00 2001 From: hugo gogo Date: Tue, 18 Oct 2022 23:44:34 +0200 Subject: [PATCH] pure node act like express --- tests/tests_hugo/pure_node/server.js | 63 ++++++++++++++++++---------- 1 file changed, 40 insertions(+), 23 deletions(-) diff --git a/tests/tests_hugo/pure_node/server.js b/tests/tests_hugo/pure_node/server.js index bddc99d2..d1787344 100644 --- a/tests/tests_hugo/pure_node/server.js +++ b/tests/tests_hugo/pure_node/server.js @@ -3,7 +3,7 @@ const http = require('http') const fs = require('fs') const url = require('url') -const sendMyFile = (file, res) => { +const sendFile = (file, res) => { fs.readFile(file, (err, data) => { if (!err) { res.writeHead(200, { @@ -25,9 +25,7 @@ const sendMyFile = (file, res) => { // // if (req.method === "GET") { // if (pathName === "/") -// sendMyFile(__dirname + "/index.html", res) -// else if (pathName === "/index.html") -// sendMyFile(__dirname + "/index.html", res) +// sendFile(__dirname + "/index.html", res) // else // { // res.writeHead(404) @@ -36,28 +34,47 @@ const sendMyFile = (file, res) => { // } //}) - -let myExpress = () => { - return http.createServer((req, res) => { - let pathName = url.parse(req.url).pathname - if (req.method === "GET") { - if (pathName === "/") - sendMyFile(__dirname + "/index.html", res) - else - { - res.writeHead(404) - res.end('wrong url') +class customServer { + constructor() { + this._gets = {}; + this._posts = {}; + this._putss = {}; + this._deletes = {}; + + this._server = http.createServer((req, res) => { + const pathName = url.parse(req.url).pathname; + + if (req.method === "GET" && this._gets[pathName]) { + this._gets[pathName](req, res); } - } - }) + else if (req.method === "POST" && this._posts[pathName]) { + this._gets[pathName](req, res); + } + else if (req.method === "PUT" && this._puts[pathName]) { + this._gets[pathName](req, res); + } + else if (req.method === "DELETE" && this._deletes[pathName]) { + this._gets[pathName](req, res); + } else { + res.writeHead(404) + res.end('not found'); + } + }) + + } + + get(url, callback) { this._gets[url] = callback; } + post(url, callback) { this._posts[url] = callback; } + add(url, callback) { this._puts[url] = callback; } + delete(url, callback) { this._deletes[url] = callback; } + + listen(port, callback) { this._server.listen(port, callback) } } - -//server.get('/', (req, res) => { -// res.sendFile(__dirname + "/" + "index.html") -//}); - -const server = myExpress(); + +const server = new customServer(); +server.get("/", (req, res) => sendFile(__dirname + "/index.html", res)); const port = 3001; +//server.listen(port); server.listen(port, console.log(`listening on port ${port}`));