express() Works Internally in Node.jsExpress is a popular backend web framework built on top of Node.js that simplifies routing, middleware, and server creation.
To understand Express better, letβs see a simplified internal version of how express() might work.
express()?The express() function returns an application object (usually named app) that gives access to important methods like:
app.get() β create GET routeapp.post() β create POST routeapp.listen() β start the HTTP serverSo when we use:
const app = express();
We are actually creating an object that stores routes and can run a server.
express()?app.listen()// pretend this is inside express.js function express() { const app = {}; // storing all routes here app.routes = []; // add GET route creator app.get = function(path, handler) { app.routes.push({ method: "GET", path, handler }); }; // add POST route creator app.post = function(path, handler) { app.routes.push({ method: "POST", path, handler }); }; // method to start the server app.listen = function(port, callback) { // internally uses Node http server const http = require("http"); const server = http.createServer((req, res) => { const matchedRoute = app.routes.find( r => r.method === req.method && r.path === req.url ); if (matchedRoute) { matchedRoute.handler(req, res); } else { res.end("Route Not Found"); } }); server.listen(port, callback); }; return app; // <--- this is what express() returns } module.exports = express;
express() returns an object called appapp stores routes and exposes methods like get(), post(), and listen()http module to create a server