how to parse incoming req by streaming parsing the chunks data

hey gusys so im a intermediate dev , im building my own expressjs & fastify type web server library.

but my bottleneck is that my library has to wait for full req to come then parse it by using another func.but i want to parse it by chunks

let me explain like – as data comes in chunk to my lib so it should not wait for full req rather it should parse that req immediately and as data come in chunks it should parse , so by this algo my library doesn’t have to wait.

here is code –


import net from "net";
import ResponseHandler from "./responseHandler.js";
import { createConnectionHandler } from "./handleConnection.js";
import Trie from "./trie.js";

class Maya {
  constructor() {
    this.routes = {
      GET: {},
      POST: {},
      PUT: {},
      DELETE: {},
    };
    this.middlewares = {};
    this.ResponseHandler = ResponseHandler;
    this.isBodyParse = false;
    this.compiledMiddlewares = [];
    this.compiledRoutes = {};
  }
  compile() {
    // console.log("Compiling middlewares and routes...");

    // Preprocess middlewares
    this.compiledMiddlewares = Object.entries(this.middlewares).sort(([a], [b]) => b.length - a.length);

    // console.log("Compiled middlewares:", this.compiledMiddlewares);

    // Preprocess routes by method
    for (const method in this.routes) {
          this.compiledRoutes[method] = Object.entries(this.routes[method])
            .sort(([a], [b]) => b.length - a.length);
        }
  }

  listen(port = 3000, callback) {
    this.compile();
    const handleConnection = createConnectionHandler(this, this.isBodyParse);
    const server = net.createServer((socket) => handleConnection(socket));

    server.listen(port, () => {
      if (typeof callback === "function") {
        return callback();
      }
    });
  }

  use(pathORhandler, handler) {
    if (typeof pathORhandler === "string") {
      this.middlewares[pathORhandler] = handler;
    } else {
      this.middlewares["/"] = pathORhandler;
    }
  }

  bodyParse() {
    this.isBodyParse = true;
  }

  get(path, handler) {
    this.routes.GET[path] = handler;
  }

  post(path, handler) {
    this.routes.POST[path] = handler;
  }

  put(path, handler) {
    this.routes.PUT[path] = handler;
  }

  delete(path, handler) {
    this.routes.DELETE[path] = handler;
  }
}

export default Maya;
// this is req parser 
import Cache from "./cache.js";

export function parseRequest(requestBuffer) {
  const cache = new Cache();
// console.log(requestBuffer)
  const req = requestBuffer.toString()
  // console.log(requestBuffer)

  // Split headers and body
  const [headerSection, body] = req.split("rnrn", 2);

  if (!headerSection) {
    return error({ error: "Invalid request format: Missing header section" });
  }

  // spit headers into two line
  const [requestLine, ...headerLine] = headerSection.split("rn");
  if (!requestLine) {
    return error({ error: "Invalid request format: Missing request line" });
  }
  // parse request line
  const [method, path, version] = requestLine.split(" ");
  if (!method || !path || !version) {
    return error({ error: "Invalid request format: Incomplete request line" });
  }

  const [url, queryString] = path.split("?", 2);
  const queryParams = new URLSearchParams(queryString);

  //  generate cache key
  const cacheKey = `${method}:${url}?${queryString}:${JSON.stringify(headerLine)}`;

  if (method === "GET") {
    const cachedResponse = cache.getCached(cacheKey);
    if (cachedResponse) {
      return cachedResponse;
    }
  }

  // parse headers and cookie
  const headers = {};
  const Cookies = {};
  for (const line of headerLine) {
    const [key, value] = line.split(": ");
    headers[key.toLowerCase()] = value;
    if (key.toLowerCase() === "cookie") {
      value.split(";").forEach((cookie) => {
        const [Cookiekey, Cookievalue] = cookie.trim().split("=");
        Cookies[Cookiekey] = decodeURIComponent(Cookievalue);
      });
    }
  }

  let parsedBody;
  const contentType = headers["content-type"];
  if (body) {
    if (contentType === "application/json") {
      try {
        parsedBody = JSON.parse(body);
      } catch (error) {
        return { error: "Invalid JSON format" };
      }
    } else if (contentType === "application/x-www-form-urlencoded") {
      parsedBody = Object.fromEntries(new URLSearchParams(body));
    } else {
      parsedBody = body; 
    }
  }

  const queryParamsObject = {};
  for (const [key, value] of queryParams.entries()) {
    queryParamsObject[key] = value;
  }

  const res = {
    method,
    path: decodeURIComponent(path),
    version,
    headers,
    body: parsedBody,
    query: queryParams,
    Cookies,
  };

  if (method === "GET") {
    cache.setCache(cacheKey, res);
  }
  return res;
}

i tried to solve my problem but i couldnt

New contributor

pradeep kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật