Make your own express-like webserver in nodejs with only builtin library (part 1)
The best way to learn something about the language that you choose is to recreate their own external library with only their standard library with that we understand about the language more. In this article i will recreating one of javascript web server library express-js but with some difference and more simple version from real express js i will name it express-like, you can follow along if you want to make express-like on your own.
The first move is creating new directory or folder call express and execute command pnpm init for init the project you can use your favorite package manager, i'm choosing pnpm in this project.
mkdir express-like && cd express-like pnpm init
this make file name package.json and modify that to look like this
{ "name": "express-like", "version": "0.0.0", "description": "", "type": "module", "main": "main.js", "scripts": { "start": "node ." }, "keywords": [], "author": "arya dewangga puja", "license": "ISC", "packageManager": "pnpm@10.9.0" } // --> package.json
After that lest jump into main.js and express-like.js file.
import {Express} from "./express-like.js" // --> main.js (create a new file)
class Express { constructor() { this.routes = {} } } export {Express} // --> express-like.js (create new file)
First we create an class called Express inside that we init some attribute, but for now we just need one attribute routes attribute, routes is where everything store from function call like app.get(route, handler)
app.post("path",function)
is store method, path and handler in object. the object look like this
"/path": { method: "GET", handler: functionCallback }
import {Express} from "./express-like.js" const app = new Express() app.listen() // --> main.js (create new app)
import http from "node:http" class Express { constructor() { // --> express-like.js (import htts add in top of file)
class Express { ... listen(port = 8080) { http.createServer((request, response) => { response.write("<h1> Hello World </h1>") response.end() }) .listen(port) console.log(`server listen on port ${port}`) } } // --> express-like.js (add listen method after constructor)
We create a listen method and call http.createServer from node:http builtin module and .listen method from http.createServer. After that try to run with pnpm start and its work.
class Express { ... get(path, handler) { this.routes[path] = { method: "GET", handler: handler } } ... } // --> express-like.js (add get method after constructor)
In get method we set path with object with attribute method and handler from parameter and method we set to GET because is a GET method.
} } class Express_Request {} class Express_Response {} export {Express} // --> express-like.js (create new class called Express_Request and Express_Response after Express class)
Lets create request and response classes for our handler paramrter to work with.
class Express_Request {} class Express_Response { constructor(http_builtinResponse) { this._response = http_builtinResponse } } export {Express} // --> express-like.js (add constructor in Express_Response)
We will work with reponse first, it is short of like a wrapper for actual http.ServerResponse from http.createServer and with that we can make some good method like .json for sending a json type lets build it.
class Express_Response { ... json(object, status = 200) { this._response.writeHead(status, { "Content-Type": "application/json", "Content-Length": JSON.stringify(object).length }) this._response.write(JSON.stringify(object)) this._response.end() } } // --> express-like.js (add json method in reponse classes add after constructor)
This will simplify our work with response json type, first we add 2 header a content type and content length those two tell the browser or even other application the response type and length of that response.
class Express { ... listen(port = 8080) { http.createServer((request, response) => { const path = request.url if (this.routes[path]) { this.routes[path].handler(new Express_Request(), new Express_Response(response)) } else { new Express_Response(response).json({ERROR: "404 NOT FOUND"}, 404) } response.end() }) .listen(port) console.log(`server listen on port ${port}`) } } // --> express-like.js (change a listen method in Express classes)
Lets change listen method in our Express class litle bit of explanation here in callback from http.createServer we first get path from request.url, yeah i know but i love call it path over url, after that we check path is in this.routes or not if yes call the handler from that path if not send and json with json that tell Error 404 NOT FOUND, lets give it a try but first lets make some handler for path / and path /hello
import {Express} from "./express-like.js" const app = new Express() app.get("/", (request, response) => { response.json({messsage: "Welcome to express-like"}) }) app.get("/hello", (request, response) => { response.json({messsage: "Hello World!"}) }) app.listen() // --> main.js (add handler)
It's works. For now Express-like just check a path not a method like .post .delete etc but we build it letten on next chapter. See you in next chapter (Sorry about my bad english). Go to explore and make your own .post etc how check method type free to play
Top comments (0)