Create a Server using net module from Node JS

import * as net from 'net'
 
const server = net.createServer((socket) => {
  socket.on("close", () => {
    socket.end()
  })
})
 
server.listen(4221, "localhost")

Respond with 200 status for any API Request

To send a response from the server, you can use socket.write

HTTP Response

HTTP Response is made up of three parts, each separated by a CRLF (\r\n):

  1. Status line
  2. Zero or more headers each ending with CRLF
  3. Optional Response Body
const server = net.createServer((socket) => {
  socket.write("HTTP/1.1 200 OK\r\n\r\n")
  socket.on("close", () => {
    socket.end()
  })
})

Extract URL Path

HTTP Request

HTTP Request is made up of three parts, each separated by a CRLF (\r\n):

  1. Request line
  2. Zero or more headers, each ending with a CRLF
  3. Optional Request Body

Example HTTP Request:

GET /index.html HTTP/1.1\r\nHost: localhost:4221\r\nUser-Agent: curl/7.64.1\r\nAccept: */*\r\n\r\n

Here’s the breakdown of the request

// Request line
GET                          // HTTP method
/index.html                  // Request target
HTTP/1.1                     // HTTP version
\r\n                         // CRLF that marks the end of the request line
 
// Headers
Host: localhost:4221\r\n     // Header that specifies the server's host and port
User-Agent: curl/7.64.1\r\n  // Header that describes the client's user agent
Accept: */*\r\n              // Header that specifies which media types the client can accept
\r\n                         // CRLF that marks the end of the headers
 
// Request body (empty)

Note that each header ends in a CRLF and the entire header section also ends with CRLF

To read the request

const server = net.createServer((socket) => {
  socket.on("data", (data) => {
    const request = data.toString()
    const [method, path] = request.split(" ")
 
    // you can do socket.write
    socket.write("HTTP/1.1 200 OK\r\n\r\n")
  })
 
  socket.on("close", () => {
    socket.end()
  })
})