DEV Community

Md.  Raihan Hossain Jibon
Md. Raihan Hossain Jibon

Posted on

How express.js works

In this post, we will go through the source code of express, and try to understand how it works under the hood. Studying how a popular open source library works, will help us make better applications using it, and reduces some of the “magic” involved

when using it.

The “Hello World” example
Let’s use the “Hello world” example given in the official website to form a starting point for digging into the source code:

const express = require("express")
const app = express()

app.get("/", (req, res) => res.send("Hello World!"))

app.listen(3000, () => console.log("Example app listening on port 3000!"))
Enter fullscreen mode Exit fullscreen mode

Creating a new express application

The var app = express() statement creates a new express application for you. The createApplication function from the lib/express.js file is the default export, which we see as the express() function call.

Some of the important bits are:

const mixin = require("merge-descriptors")
const proto = require("./application")

function createApplication() {
    const app = function(req, res, next) {
        app.handle(req, res, next)
    }
    mixin(app, proto, false)
    return app
}
Enter fullscreen mode Exit fullscreen mode

Starting the HTTP server

After setting up the routes, the server has to be started. In our example, we call the app.listen method, with the port number, and callback function as the arguments. To understand this method, we can see lib/application.js. The gist of it is:

app.listen = function listen() {
    var server = http.createServer(this)
    return server.listen.apply(server, arguments)
}
Enter fullscreen mode Exit fullscreen mode

Hopefully, this post helped you in understanding the important aspects of the source code, which you can use to understand the rest of it.

If there are any libraries or frameworks whose internal workings you feel deserve an explanation, let me know in the comments.

Oldest comments (0)