Building a Typescript HTTP server

Table of contents

No heading

No headings in the article.

MDN defines a web server as:

  1. On the hardware side, a web server is a computer that stores web server software and a website's component files (for example, HTML documents, images, CSS stylesheets, and JavaScript files). A web server connects to the Internet and supports physical data interchange with other devices connected to the web.

  2. On the software side, a web server includes several parts that control how web users access hosted files. At a minimum, this is an HTTP server. An HTTP server is a software that understands URLs (web addresses) and HTTP (the protocol your browser uses to view webpages). An HTTP server can be accessed through the domain names of the websites it stores, and it delivers the content of these hosted websites to the end user's device.

To start a web server in node js with the http module

import { createServer , IncomingMessage , ServerResponse } from 'http'

const port: number = 5050

const server = createServer(( request:IncomingMessage , response:ServerResponse) => {
  response.write("Hello, World! \n", (error:Error) => {
    if(error){
      console.error(error)
    }
  })
  response.end()
})

server.listen(port)

The server gets a request from a client and returns a response to the client.

Data is sent to the server via the request, the data can be a JSON with a POST request, or plain HTML and CSS files can be requested with a GET request.

More on request methods here

The response returns data to the client(the browser in this case), and we write to the response with response.write() and signal that all the data that needs to be sent is sent with response.end()

The server.listen(port) method allows the server to listen for requests on the port 5050 and visiting localhost:5050 in the browser after running the code, would display the message Hello, World!

I would be building a simple router for the server next😊.

Full code in GitHub