├── test
├── files
│ ├── test.txt
│ ├── audio.m4a
│ ├── styles.css
│ └── index.html
├── redirect.test.ts
├── files.test.ts
├── render.test.ts
├── parseJSON.test.ts
├── serveStatic.test.ts
├── errors.test.ts
├── middleware.test.ts
├── routeMiddleware.test.ts
└── router.test.ts
├── .npmignore
├── .gitignore
├── tsconfig.tests.json
├── lib
├── utils
│ ├── index.ts
│ ├── parseJSON.ts
│ ├── serveStatic.ts
│ └── render.ts
├── types.ts
└── index.ts
├── tsconfig.json
├── LICENSE
├── package.json
└── README.md
/test/files/test.txt:
--------------------------------------------------------------------------------
1 | This is a test file.
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | .gitignore
2 | test
3 | examples
4 | private.txt
5 | .DS_Store
6 | .vscode
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | private.txt
3 | node_modules
4 | playground.js
5 | dist
6 | .vscode
--------------------------------------------------------------------------------
/test/files/audio.m4a:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/agile8118/cpeak/HEAD/test/files/audio.m4a
--------------------------------------------------------------------------------
/test/files/styles.css:
--------------------------------------------------------------------------------
1 | /* some styles for testing... */
2 | .my-class {
3 | color: red;
4 | }
5 |
6 | .my-class-2 {
7 | color: blue;
8 | }
9 |
10 |
--------------------------------------------------------------------------------
/tsconfig.tests.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "compilerOptions": {
4 | "noEmit": true,
5 | "types": ["mocha", "node"]
6 | },
7 | "include": ["test/**/*.ts"]
8 | }
9 |
--------------------------------------------------------------------------------
/lib/utils/index.ts:
--------------------------------------------------------------------------------
1 | import { parseJSON } from "./parseJSON";
2 | import { serveStatic } from "./serveStatic";
3 | import { render } from "./render";
4 |
5 | export { serveStatic, parseJSON, render };
6 |
--------------------------------------------------------------------------------
/test/files/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | {{ title }}
7 |
8 |
9 | {{ body }}
10 |
11 |
12 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2022",
4 | "lib": ["ES2022"],
5 | "module": "ES2022",
6 | "moduleResolution": "Bundler",
7 | "strict": true,
8 |
9 | "declaration": true,
10 | "declarationMap": false,
11 | "sourceMap": true,
12 | "removeComments": true,
13 |
14 | "outDir": "dist",
15 | "rootDir": "lib",
16 | "verbatimModuleSyntax": false,
17 | "skipLibCheck": true
18 | },
19 | "include": ["lib/**/*.ts"],
20 | "exclude": ["node_modules", "dist"]
21 | }
22 |
--------------------------------------------------------------------------------
/lib/utils/parseJSON.ts:
--------------------------------------------------------------------------------
1 | import type { CpeakRequest, CpeakResponse, Next } from "../types";
2 |
3 | // Parsing JSON
4 | const parseJSON = (req: CpeakRequest, res: CpeakResponse, next: Next) => {
5 | // This is only good for bodies that their size is less than the highWaterMark value
6 |
7 | function isJSON(contentType: string = "") {
8 | // Remove any params like "; charset=UTF-8"
9 | const [type] = contentType.split(";");
10 | return (
11 | type.trim().toLowerCase() === "application/json" ||
12 | /\+json$/i.test(type.trim())
13 | );
14 | }
15 |
16 | if (!isJSON(req.headers["content-type"] as string)) return next();
17 |
18 | let body = "";
19 | req.on("data", (chunk: Buffer) => {
20 | body += chunk.toString("utf-8");
21 | });
22 |
23 | req.on("end", () => {
24 | body = JSON.parse(body);
25 | req.body = body;
26 | return next();
27 | });
28 | };
29 |
30 | export { parseJSON };
31 |
--------------------------------------------------------------------------------
/test/redirect.test.ts:
--------------------------------------------------------------------------------
1 | import assert from "node:assert";
2 | import supertest from "supertest";
3 | import cpeak from "../lib/";
4 |
5 | import type { CpeakRequest, CpeakResponse } from "../lib/types";
6 |
7 | const PORT = 7543;
8 | const request = supertest(`http://localhost:${PORT}`);
9 |
10 | describe("Redirecting to a new URL with res.redirect function", function () {
11 | let server: cpeak;
12 |
13 | before(function (done) {
14 | server = new cpeak();
15 |
16 | server.route(
17 | "get",
18 | "/old-route",
19 | (req: CpeakRequest, res: CpeakResponse) => {
20 | res.redirect("/new-route");
21 | }
22 | );
23 |
24 | server.listen(PORT, done);
25 | });
26 |
27 | after(function (done) {
28 | server.close(done);
29 | });
30 |
31 | it("should redirect to the new route", async function () {
32 | const res = await request.get("/old-route");
33 | assert.strictEqual(res.status, 302);
34 | assert.strictEqual(res.headers["location"], "/new-route");
35 | });
36 | });
37 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Cododev Technology Inc.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/test/files.test.ts:
--------------------------------------------------------------------------------
1 | import assert from "node:assert";
2 | import supertest from "supertest";
3 | import fs from "node:fs/promises";
4 | import cpeak from "../lib/";
5 |
6 | import type { CpeakRequest, CpeakResponse, HandleErr } from "../lib/types";
7 |
8 | const PORT = 7543;
9 | const request = supertest(`http://localhost:${PORT}`);
10 |
11 | describe("Returning files with sendFile", function () {
12 | let server: cpeak;
13 |
14 | before(function (done) {
15 | server = new cpeak();
16 |
17 | server.route("get", "/file", (req: CpeakRequest, res: CpeakResponse) => {
18 | res.status(200).sendFile("./test/files/test.txt", "text/plain");
19 | });
20 |
21 | server.listen(PORT, done);
22 | });
23 |
24 | after(function (done) {
25 | server.close(done);
26 | });
27 |
28 | it("should get a file as the response with the correct MIME type", async function () {
29 | const res = await request.get("/file");
30 |
31 | const fileContent = await fs.readFile("./test/files/test.txt", "utf-8");
32 |
33 | assert.strictEqual(res.status, 200);
34 | assert.strictEqual(res.headers["content-type"], "text/plain");
35 | assert.strictEqual(res.text, fileContent);
36 | });
37 | });
38 |
--------------------------------------------------------------------------------
/test/render.test.ts:
--------------------------------------------------------------------------------
1 | import assert from "node:assert";
2 | import supertest from "supertest";
3 | import cpeak, { render } from "../lib/";
4 |
5 | import type { CpeakRequest, CpeakResponse } from "../lib/types";
6 |
7 | const PORT = 7543;
8 | const request = supertest(`http://localhost:${PORT}`);
9 |
10 | describe("Rendering a template with render middleware", function () {
11 | let server: cpeak;
12 |
13 | before(function (done) {
14 | server = new cpeak();
15 |
16 | server.beforeEach(render());
17 |
18 | server.route("get", "/", (req: CpeakRequest, res: CpeakResponse) => {
19 | return res.render(
20 | `./test/files/index.html`,
21 | {
22 | title: "Home",
23 | body: "Welcome to the Home Page",
24 | },
25 | "text/html"
26 | );
27 | });
28 |
29 | server.listen(PORT, done);
30 | });
31 |
32 | after(function (done) {
33 | server.close(done);
34 | });
35 |
36 | it("should render the correct the HTML file with the variables correctly injected", async function () {
37 | const res = await request.get("/");
38 |
39 | assert.equal(res.status, 200);
40 | assert.match(res.headers["content-type"] ?? "", /^text\/html\b/);
41 |
42 | assert.ok(res.text.includes("Home"));
43 | assert.ok(res.text.includes("Welcome to the Home Page
"));
44 | });
45 | });
46 |
--------------------------------------------------------------------------------
/test/parseJSON.test.ts:
--------------------------------------------------------------------------------
1 | import assert from "node:assert";
2 | import supertest from "supertest";
3 | import cpeak, { parseJSON } from "../lib/";
4 |
5 | import type { CpeakRequest, CpeakResponse } from "../lib/types";
6 |
7 | const PORT = 7543;
8 | const request = supertest(`http://localhost:${PORT}`);
9 |
10 | describe("Parsing request bodies with parseJSON", function () {
11 | let server: cpeak;
12 |
13 | before(function (done) {
14 | server = new cpeak();
15 |
16 | server.beforeEach(parseJSON);
17 |
18 | server.route(
19 | "post",
20 | "/do-something",
21 | (req: CpeakRequest, res: CpeakResponse) => {
22 | res.status(205).json({ receivedData: req.body });
23 | }
24 | );
25 |
26 | server.listen(PORT, done);
27 | });
28 |
29 | after(function (done) {
30 | server.close(done);
31 | });
32 |
33 | it("should return the same data that was sent in request body as JSON", async function () {
34 | const obj = {
35 | key1: "value1",
36 | key2: 42,
37 | key3: {
38 | nestedKey1: "nestedValue1",
39 | nestedKey2: ["arrayValue1", "arrayValue2", 1000],
40 | },
41 | key4: true,
42 | };
43 |
44 | const res = await request.post("/do-something").send(obj);
45 |
46 | assert.strictEqual(res.status, 205);
47 | assert.deepStrictEqual(res.body.receivedData, obj);
48 | });
49 | });
50 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cpeak",
3 | "version": "2.4.0",
4 | "description": "A minimal and fast Node.js HTTP framework.",
5 | "type": "module",
6 | "scripts": {
7 | "build": "tsup lib/index.ts --format esm --dts --sourcemap --out-dir dist --clean",
8 | "dev": "tsup lib/index.ts --watch --format esm --dts --sourcemap --out-dir dist",
9 | "test": "tsx ./node_modules/mocha/bin/_mocha --extension ts \"test/**/*.test.ts\""
10 | },
11 | "repository": {
12 | "type": "git",
13 | "url": "https://github.com/agile8118/cpeak.git"
14 | },
15 | "bugs": {
16 | "url": "https://github.com/agile8118/cpeak/issues"
17 | },
18 | "homepage": "https://github.com/agile8118/cpeak#readme",
19 | "main": "./dist/index.js",
20 | "module": "./dist/index.js",
21 | "types": "./dist/index.d.ts",
22 | "exports": {
23 | ".": {
24 | "import": "./dist/index.js",
25 | "types": "./dist/index.d.ts"
26 | }
27 | },
28 | "files": [
29 | "dist",
30 | "lib",
31 | "README.md",
32 | "LICENSE"
33 | ],
34 | "author": "Cododev Technology",
35 | "license": "MIT",
36 | "keywords": [
37 | "cpeak",
38 | "backend",
39 | "router",
40 | "nodejs",
41 | "http",
42 | "framework"
43 | ],
44 | "devDependencies": {
45 | "@types/mocha": "^10.0.10",
46 | "@types/node": "^24.3.0",
47 | "@types/supertest": "^6.0.3",
48 | "mocha": "^10.8.2",
49 | "supertest": "^7.1.4",
50 | "ts-node": "^10.9.2",
51 | "tsup": "^8.5.0",
52 | "tsx": "^4.20.5",
53 | "typescript": "^5.9.2"
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/test/serveStatic.test.ts:
--------------------------------------------------------------------------------
1 | import assert from "node:assert";
2 | import supertest from "supertest";
3 | import fs from "node:fs/promises";
4 | import cpeak, { serveStatic } from "../lib/";
5 |
6 | const PORT = 7543;
7 | const request = supertest(`http://localhost:${PORT}`);
8 |
9 | describe("Serving static files with serveStatic", function () {
10 | let server: cpeak;
11 |
12 | before(function (done) {
13 | server = new cpeak();
14 |
15 | server.beforeEach(serveStatic("./test/files", { m4a: "audio/mp4" }));
16 |
17 | server.listen(PORT, done);
18 | });
19 |
20 | after(function (done) {
21 | server.close(done);
22 | });
23 |
24 | it("should return the correct file with the correct MIME type", async function () {
25 | const textRes = await request.get("/test.txt");
26 | const cssRes = await request.get("/styles.css");
27 |
28 | const fileTextContent = await fs.readFile("./test/files/test.txt", "utf-8");
29 | const fileCssContent = await fs.readFile(
30 | "./test/files/styles.css",
31 | "utf-8"
32 | );
33 |
34 | assert.strictEqual(textRes.status, 200);
35 | assert.strictEqual(textRes.headers["content-type"], "text/plain");
36 | assert.strictEqual(textRes.text, fileTextContent);
37 |
38 | assert.strictEqual(cssRes.status, 200);
39 | assert.strictEqual(cssRes.headers["content-type"], "text/css");
40 | assert.strictEqual(cssRes.text, fileCssContent);
41 | });
42 |
43 | it("should return the correct file with the specified MIME type by the developer", async function () {
44 | const res = await request.get("/audio.m4a");
45 |
46 | // read the file as binary
47 | const fileBuffer = await fs.readFile("./test/files/audio.m4a");
48 |
49 | assert.strictEqual(res.status, 200);
50 | assert.strictEqual(res.headers["content-type"], "audio/mp4");
51 | assert.deepStrictEqual(res.body, fileBuffer);
52 | });
53 | });
54 |
--------------------------------------------------------------------------------
/lib/types.ts:
--------------------------------------------------------------------------------
1 | import { IncomingMessage, ServerResponse } from "node:http";
2 | import CpeakClass from "./index";
3 |
4 | export type Cpeak = InstanceType;
5 |
6 | // Extending Node.js's Request and Response objects to add our custom properties
7 | export type StringMap = Record;
8 |
9 | export interface CpeakRequest extends IncomingMessage {
10 | params: StringMap;
11 | vars?: StringMap;
12 | body?: unknown;
13 | [key: string]: any; // allow developers to add their onw extensions (e.g. req.test)
14 |
15 | // For express frameworks compatibility:
16 | query: StringMap;
17 | }
18 |
19 | export interface CpeakResponse extends ServerResponse {
20 | sendFile: (path: string, mime: string) => Promise;
21 | status: (code: number) => CpeakResponse;
22 | redirect: (location: string) => CpeakResponse;
23 | json: (data: any) => void;
24 | [key: string]: any; // allow developers to add their onw extensions (e.g. res.test)
25 | }
26 |
27 | export type Next = (err?: any) => void;
28 | export type HandleErr = (err: any) => void;
29 |
30 | // beforeEach middleware: (req, res, next)
31 | export type Middleware = (
32 | req: CpeakRequest,
33 | res: CpeakResponse,
34 | next: Next
35 | ) => void;
36 |
37 | // Route middleware: (req, res, next, handleErr)
38 | export type RouteMiddleware = (
39 | req: CpeakRequest,
40 | res: CpeakResponse,
41 | next: Next,
42 | handleErr: HandleErr
43 | ) => void | Promise;
44 |
45 | // Route handlers: (req, res, handleErr)
46 | export type Handler = (
47 | req: CpeakRequest,
48 | res: CpeakResponse,
49 | handleErr: HandleErr
50 | ) => void | Promise;
51 |
52 | // For a route object value in Cpeak.routes. The key is the method name.
53 | export interface Route {
54 | path: string;
55 | regex: RegExp;
56 | middleware: RouteMiddleware[];
57 | cb: Handler;
58 | }
59 |
60 | // For Cpeak.routes:
61 | export interface RoutesMap {
62 | [method: string]: Route[];
63 | }
64 |
--------------------------------------------------------------------------------
/test/errors.test.ts:
--------------------------------------------------------------------------------
1 | import assert from "node:assert";
2 | import supertest from "supertest";
3 |
4 | import cpeak from "../lib/";
5 |
6 | import type { CpeakRequest, CpeakResponse, HandleErr } from "../lib/types";
7 |
8 | const PORT = 7543;
9 | const request = supertest(`http://localhost:${PORT}`);
10 |
11 | describe("Error handling with handleErr", function () {
12 | let server: cpeak;
13 |
14 | before(function (done) {
15 | server = new cpeak();
16 |
17 | const mid1 = (
18 | req: CpeakRequest,
19 | res: CpeakResponse,
20 | next: () => void,
21 | handleErr: HandleErr
22 | ) => {
23 | const value = req.params.value;
24 |
25 | if (value === "random")
26 | return handleErr({ status: 401, message: "another error msg" });
27 |
28 | next();
29 | };
30 |
31 | server.route(
32 | "patch",
33 | "/foo/:bar",
34 | mid1,
35 | (req: CpeakRequest, res: CpeakResponse, handleErr: HandleErr) => {
36 | const bar = req.vars?.bar;
37 |
38 | console.log("-----");
39 | console.log(bar);
40 |
41 | if (bar === "random") {
42 | return handleErr({ status: 403, message: "an error msg" });
43 | }
44 |
45 | return res.status(200).json({ bar });
46 | }
47 | );
48 |
49 | server.handleErr((error: any, req: CpeakRequest, res: CpeakResponse) => {
50 | return res.status(error.status).json({ error: error.message });
51 | });
52 |
53 | server.listen(PORT, done);
54 | });
55 |
56 | after(function (done) {
57 | server.close(done);
58 | });
59 |
60 | it("should get an error using the handleErr function from a router", async function () {
61 | const res = await request.patch("/foo/random");
62 | assert.strictEqual(res.status, 403);
63 | assert.deepStrictEqual(res.body, { error: "an error msg" });
64 | });
65 |
66 | it("should get an error using the handleErr function from a middleware", async function () {
67 | const res = await request.patch("/foo/random?value=random");
68 | assert.strictEqual(res.status, 401);
69 | assert.deepStrictEqual(res.body, { error: "another error msg" });
70 | });
71 | });
72 |
--------------------------------------------------------------------------------
/test/middleware.test.ts:
--------------------------------------------------------------------------------
1 | import assert from "node:assert";
2 | import supertest from "supertest";
3 | import cpeak from "../lib/";
4 |
5 | import type { CpeakRequest, CpeakResponse } from "../lib/types";
6 |
7 | const PORT = 7543;
8 | const request = supertest(`http://localhost:${PORT}`);
9 |
10 | describe("Middleware functions", function () {
11 | let server: cpeak;
12 |
13 | before(function (done) {
14 | server = new cpeak();
15 |
16 | server.beforeEach((req, res, next) => {
17 | const value = req.params.value;
18 |
19 | if (value === "random")
20 | return res.status(400).json({ error: "an error msg" });
21 |
22 | next();
23 | });
24 |
25 | server.beforeEach((req, res, next) => {
26 | req.foo = "text";
27 | next();
28 | });
29 |
30 | server.beforeEach((req, res, next) => {
31 | res.unauthorized = () => {
32 | res.statusCode = 401;
33 | return res;
34 | };
35 | next();
36 | });
37 |
38 | server.route("get", "/bar", (req: CpeakRequest, res: CpeakResponse) => {
39 | res.status(200).json({ message: req.foo });
40 | });
41 |
42 | server.route(
43 | "get",
44 | "/bar-more",
45 | (req: CpeakRequest, res: CpeakResponse) => {
46 | res.unauthorized().json({});
47 | }
48 | );
49 |
50 | server.listen(PORT, done);
51 | });
52 |
53 | after(function (done) {
54 | server.close(done);
55 | });
56 |
57 | it("should modify the req object with a new property", async function () {
58 | const res = await request.get("/bar");
59 | assert.strictEqual(res.status, 200);
60 | assert.strictEqual(res.body.message, "text");
61 | });
62 |
63 | it("should modify the res object with a new method", async function () {
64 | const res = await request.get("/bar-more");
65 | assert.strictEqual(res.status, 401);
66 | });
67 |
68 | it("should exit the middleware and route chain if a middleware wants to", async function () {
69 | const res = await request.get("/bar?value=random");
70 | assert.strictEqual(res.status, 400);
71 | assert.strictEqual(res.body.message, undefined);
72 | assert.deepStrictEqual(res.body, { error: "an error msg" });
73 | });
74 | });
75 |
--------------------------------------------------------------------------------
/test/routeMiddleware.test.ts:
--------------------------------------------------------------------------------
1 | import assert from "node:assert";
2 | import supertest from "supertest";
3 | import cpeak from "../lib/";
4 |
5 | import type { CpeakRequest, CpeakResponse } from "../lib/types";
6 |
7 | const PORT = 7543;
8 | const request = supertest(`http://localhost:${PORT}`);
9 |
10 | describe("Route middleware functions", function () {
11 | let server: cpeak;
12 |
13 | before(function (done) {
14 | server = new cpeak();
15 |
16 | const mid1 = (req: CpeakRequest, res: CpeakResponse, next: () => void) => {
17 | const value = req.params.value;
18 |
19 | if (value === "random")
20 | return res.status(400).json({ error: "an error msg" });
21 |
22 | next();
23 | };
24 |
25 | const mid2 = (req: CpeakRequest, res: CpeakResponse, next: () => void) => {
26 | req.foo = "text";
27 | next();
28 | };
29 |
30 | const mid3 = (req: CpeakRequest, res: CpeakResponse, next: () => void) => {
31 | res.unauthorized = () => {
32 | res.statusCode = 401;
33 | return res;
34 | };
35 | next();
36 | };
37 |
38 | server.route(
39 | "get",
40 | "/bar",
41 | mid1,
42 | mid2,
43 | (req: CpeakRequest, res: CpeakResponse) => {
44 | res.status(200).json({ message: req.foo });
45 | }
46 | );
47 |
48 | server.route(
49 | "get",
50 | "/bar-more",
51 | mid3,
52 | (req: CpeakRequest, res: CpeakResponse) => {
53 | res.unauthorized().json({});
54 | }
55 | );
56 |
57 | server.listen(PORT, done);
58 | });
59 |
60 | after(function (done) {
61 | server.close(done);
62 | });
63 |
64 | it("should modify the req object with a new property", async function () {
65 | const res = await request.get("/bar");
66 | assert.strictEqual(res.status, 200);
67 | assert.strictEqual(res.body.message, "text");
68 | });
69 |
70 | it("should modify the res object with a new method", async function () {
71 | const res = await request.get("/bar-more");
72 | assert.strictEqual(res.status, 401);
73 | });
74 |
75 | it("should exit the middleware and route chain if a middleware wants to", async function () {
76 | const res = await request.get("/bar?value=random");
77 | assert.strictEqual(res.status, 400);
78 | assert.strictEqual(res.body.message, undefined);
79 | assert.deepStrictEqual(res.body, { error: "an error msg" });
80 | });
81 | });
82 |
--------------------------------------------------------------------------------
/lib/utils/serveStatic.ts:
--------------------------------------------------------------------------------
1 | import fs from "node:fs";
2 | import path from "node:path";
3 |
4 | import type { StringMap, CpeakRequest, CpeakResponse, Next } from "../types";
5 |
6 | const MIME_TYPES: StringMap = {
7 | html: "text/html",
8 | css: "text/css",
9 | js: "application/javascript",
10 | jpg: "image/jpeg",
11 | jpeg: "image/jpeg",
12 | png: "image/png",
13 | svg: "image/svg+xml",
14 | txt: "text/plain",
15 | eot: "application/vnd.ms-fontobject",
16 | otf: "font/otf",
17 | ttf: "font/ttf",
18 | woff: "font/woff",
19 | woff2: "font/woff2",
20 | };
21 |
22 | const serveStatic = (folderPath: string, newMimeTypes?: StringMap) => {
23 | // For new user defined mime types
24 | if (newMimeTypes) {
25 | Object.assign(MIME_TYPES, newMimeTypes);
26 | }
27 |
28 | function processFolder(folderPath: string, parentFolder: string) {
29 | const staticFiles: string[] = [];
30 |
31 | // Read the contents of the folder
32 | const files = fs.readdirSync(folderPath);
33 |
34 | // Loop through the files and subfolders
35 | for (const file of files) {
36 | const fullPath = path.join(folderPath, file);
37 |
38 | // Check if it's a directory
39 | if (fs.statSync(fullPath).isDirectory()) {
40 | // If it's a directory, recursively process it
41 | const subfolderFiles = processFolder(fullPath, parentFolder);
42 | staticFiles.push(...subfolderFiles);
43 | } else {
44 | // If it's a file, add it to the array
45 | const relativePath = path.relative(parentFolder, fullPath);
46 | const fileExtension = path.extname(file).slice(1);
47 | if (MIME_TYPES[fileExtension]) staticFiles.push("/" + relativePath);
48 | }
49 | }
50 |
51 | return staticFiles;
52 | }
53 |
54 | const filesArrayToFilesMap = (filesArray: string[]) => {
55 | const filesMap: Record = {};
56 | for (const file of filesArray) {
57 | const fileExtension = path.extname(file).slice(1);
58 | filesMap[file] = {
59 | path: folderPath + file,
60 | mime: MIME_TYPES[fileExtension],
61 | };
62 | }
63 | return filesMap;
64 | };
65 |
66 | // Start processing the folder
67 | const filesMap = filesArrayToFilesMap(processFolder(folderPath, folderPath));
68 |
69 | return function (req: CpeakRequest, res: CpeakResponse, next: Next) {
70 | const url = req.url;
71 | if (typeof url !== "string") return next();
72 |
73 | if (Object.prototype.hasOwnProperty.call(filesMap, url)) {
74 | const fileRoute = filesMap[url];
75 | return res.sendFile(fileRoute.path, fileRoute.mime);
76 | }
77 |
78 | next();
79 | };
80 | };
81 |
82 | export { serveStatic };
83 |
--------------------------------------------------------------------------------
/lib/utils/render.ts:
--------------------------------------------------------------------------------
1 | import fs from "node:fs/promises";
2 | import { frameworkError } from "../";
3 | import type { CpeakRequest, CpeakResponse, Next } from "../types";
4 |
5 | function renderTemplate(
6 | templateStr: string,
7 | data: Record
8 | ): string {
9 | // Initialize variables
10 | let result: (string | unknown)[] = [];
11 |
12 | let currentIndex = 0;
13 |
14 | while (currentIndex < templateStr.length) {
15 | // Find the next opening placeholder
16 | const startIdx = templateStr.indexOf("{{", currentIndex);
17 | if (startIdx === -1) {
18 | // No more placeholders, push the remaining string
19 | result.push(templateStr.slice(currentIndex));
20 | break;
21 | }
22 |
23 | // Push the part before the placeholder
24 | result.push(templateStr.slice(currentIndex, startIdx));
25 |
26 | // Find the closing placeholder
27 | const endIdx = templateStr.indexOf("}}", startIdx);
28 | if (endIdx === -1) {
29 | // No closing brace found, treat the rest as plain text
30 | result.push(templateStr.slice(startIdx));
31 | break;
32 | }
33 |
34 | // Extract the variable name
35 | const varName = templateStr.slice(startIdx + 2, endIdx).trim();
36 |
37 | // Replace the variable with its value from the data, or use an empty string if not found
38 | const replacement = data[varName] !== undefined ? data[varName] : "";
39 |
40 | // Push the replacement to the result array
41 | result.push(replacement);
42 |
43 | // Move the index past the current closing placeholder
44 | currentIndex = endIdx + 2;
45 | }
46 |
47 | // Join all parts into a final string
48 | return result.join("");
49 | }
50 |
51 | // Errors to return: recommend to not render files larger than 100KB
52 | // To Explore: Doing the operation in C++ and return the data as stream back to the client
53 | // @TODO: remove the file from static map
54 | // @TODO: escape the string to prevent XSS
55 | // @TODO: add another {{{ }}} option to not escape the string
56 | const render = () => {
57 | return function (req: CpeakRequest, res: CpeakResponse, next: Next): void {
58 | res.render = async (
59 | path: string,
60 | data: Record,
61 | mime: string
62 | ) => {
63 | // check if mime is specified, if not return an error
64 | if (!mime) {
65 | throw frameworkError(
66 | `MIME type is missing. You called res.render("${path}", ...) but forgot to provide the third "mime" argument.`,
67 | res.render
68 | );
69 | }
70 |
71 | let fileStr = await fs.readFile(path, "utf-8");
72 | const finalStr = renderTemplate(fileStr, data);
73 | res.setHeader("Content-Type", mime);
74 | res.end(finalStr);
75 | };
76 |
77 | next();
78 | };
79 | };
80 |
81 | export { render };
82 |
--------------------------------------------------------------------------------
/test/router.test.ts:
--------------------------------------------------------------------------------
1 | import assert from "node:assert";
2 | import supertest from "supertest";
3 | import cpeak from "../lib/";
4 |
5 | import type { CpeakRequest, CpeakResponse } from "../lib/types";
6 |
7 | const PORT = 7543;
8 | const request = supertest(`http://localhost:${PORT}`);
9 |
10 | describe("General route logic & URL variables and parameters", function () {
11 | let server: cpeak;
12 |
13 | before(function (done) {
14 | server = new cpeak();
15 |
16 | server.route("get", "/hello", (req: CpeakRequest, res: CpeakResponse) => {
17 | res.status(200).json({ message: "Hello, World!" });
18 | });
19 |
20 | server.route(
21 | "get",
22 | "/document/:title/more/:another/final",
23 | (req: CpeakRequest, res: CpeakResponse) => {
24 | const title = req.vars?.title;
25 | const another = req.vars?.another;
26 | const params = req.params;
27 |
28 | res.status(200).json({ title, another, params });
29 | }
30 | );
31 |
32 | server.listen(PORT, done);
33 | });
34 |
35 | after(function (done) {
36 | server.close(done);
37 | });
38 |
39 | it("should return a simple response with no variables and parameters", async function () {
40 | const res = await request.get("/hello");
41 | assert.strictEqual(res.status, 200);
42 | assert.deepStrictEqual(res.body, { message: "Hello, World!" });
43 | });
44 |
45 | it("should return a 404 for unknown routes", async function () {
46 | const res = await request.get("/unknown");
47 | assert.strictEqual(res.status, 404);
48 | assert.deepStrictEqual(res.body, {
49 | error: "Cannot GET /unknown",
50 | });
51 | });
52 |
53 | it("should return a 404 for not handled methods", async function () {
54 | const res = await request.patch("/random");
55 | assert.strictEqual(res.status, 404);
56 | assert.deepStrictEqual(res.body, {
57 | error: "Cannot PATCH /random",
58 | });
59 | });
60 |
61 | it("should return the correct URL variables and parameters", async function () {
62 | const expectedResponseBody = {
63 | title: "some-title",
64 | another: "thisISsome__more-text",
65 | params: {
66 | filter: "comments-date",
67 | page: "2",
68 | sortBy: "date-desc",
69 | tags: JSON.stringify(["nodejs", "express", "url-params"]),
70 | author: JSON.stringify({ name: "John Doe", id: 123 }),
71 | isPublished: "true",
72 | metadata: JSON.stringify({ version: "1.0.0", language: "en" }),
73 | },
74 | };
75 |
76 | const res = await request
77 | .get("/document/some-title/more/thisISsome__more-text/final")
78 | .query({
79 | filter: "comments-date",
80 | page: 2,
81 | sortBy: "date-desc",
82 | tags: JSON.stringify(["nodejs", "express", "url-params"]),
83 | author: JSON.stringify({ name: "John Doe", id: 123 }),
84 | isPublished: true,
85 | metadata: JSON.stringify({ version: "1.0.0", language: "en" }),
86 | });
87 |
88 | assert.strictEqual(res.status, 200);
89 | assert.deepStrictEqual(res.body, expectedResponseBody);
90 | });
91 | });
92 |
--------------------------------------------------------------------------------
/lib/index.ts:
--------------------------------------------------------------------------------
1 | import http from "node:http";
2 | import fs from "node:fs/promises";
3 | import { createReadStream } from "node:fs";
4 | import { pipeline } from "node:stream/promises";
5 |
6 | import { serveStatic, parseJSON, render } from "./utils";
7 |
8 | import type {
9 | StringMap,
10 | CpeakRequest,
11 | CpeakResponse,
12 | Middleware,
13 | RouteMiddleware,
14 | Handler,
15 | RoutesMap,
16 | } from "./types";
17 |
18 | // A utility function to create an error with a custom stack trace
19 | export function frameworkError(
20 | message: string,
21 | skipFn: Function,
22 | code?: string
23 | ) {
24 | const err = new Error(message) as Error & { code?: string };
25 | Error.captureStackTrace(err, skipFn);
26 |
27 | if (code) err.code = code;
28 |
29 | return err;
30 | }
31 |
32 | export enum ErrorCode {
33 | MISSING_MIME = "CPEAK_ERR_MISSING_MIME",
34 | FILE_NOT_FOUND = "CPEAK_ERR_FILE_NOT_FOUND",
35 | NOT_A_FILE = "CPEAK_ERR_NOT_A_FILE",
36 | SEND_FILE_FAIL = "CPEAK_ERR_SEND_FILE_FAIL",
37 | }
38 |
39 | class Cpeak {
40 | private server: http.Server;
41 | private routes: RoutesMap;
42 | private middleware: Middleware[];
43 | private _handleErr?: (
44 | err: unknown,
45 | req: CpeakRequest,
46 | res: CpeakResponse
47 | ) => void;
48 |
49 | constructor() {
50 | this.server = http.createServer();
51 | this.routes = {};
52 | this.middleware = [];
53 |
54 | this.server.on("request", (req: CpeakRequest, res: CpeakResponse) => {
55 | // Send a file back to the client
56 | res.sendFile = async (path: string, mime: string) => {
57 | if (!mime) {
58 | throw frameworkError(
59 | 'MIME type is missing. Use res.sendFile(path, "mime-type").',
60 | res.sendFile,
61 | ErrorCode.MISSING_MIME
62 | );
63 | }
64 |
65 | try {
66 | const stat = await fs.stat(path);
67 | if (!stat.isFile()) {
68 | throw frameworkError(
69 | `Not a file: ${path}`,
70 | res.sendFile,
71 | ErrorCode.NOT_A_FILE
72 | );
73 | }
74 |
75 | res.setHeader("Content-Type", mime);
76 | res.setHeader("Content-Length", String(stat.size));
77 |
78 | // Properly propagate stream errors and respect backpressure
79 | await pipeline(createReadStream(path), res);
80 | } catch (err: any) {
81 | if (err?.code === "ENOENT") {
82 | throw frameworkError(
83 | `File not found: ${path}`,
84 | res.sendFile,
85 | ErrorCode.FILE_NOT_FOUND
86 | );
87 | }
88 |
89 | throw frameworkError(
90 | `Failed to send file: ${path}`,
91 | res.sendFile,
92 | ErrorCode.SEND_FILE_FAIL
93 | );
94 | }
95 | };
96 |
97 | // Set the status code of the response
98 | res.status = (code: number) => {
99 | res.statusCode = code;
100 | return res;
101 | };
102 |
103 | // Redirects to a new URL
104 | res.redirect = (location: string) => {
105 | res.writeHead(302, { Location: location });
106 | res.end();
107 | return res;
108 | };
109 |
110 | // Send a json data back to the client (for small json data, less than the highWaterMark)
111 | res.json = (data: any) => {
112 | // This is only good for bodies that their size is less than the highWaterMark value
113 | res.setHeader("Content-Type", "application/json");
114 | res.end(JSON.stringify(data));
115 | };
116 |
117 | // Get the url without the URL parameters
118 | const urlWithoutParams = req.url?.split("?")[0];
119 |
120 | // Parse the URL parameters (like /users?key1=value1&key2=value2)
121 | // We put this here to also parse them for all the middleware functions
122 | const params = new URLSearchParams(req.url?.split("?")[1]);
123 |
124 | const paramsObject = Object.fromEntries(params.entries());
125 |
126 | req.params = paramsObject;
127 | req.query = paramsObject; // only for compatibility with frameworks built for express
128 |
129 | // Run all the specific middleware functions for that router only and then run the handler
130 | const runHandler = (
131 | req: CpeakRequest,
132 | res: CpeakResponse,
133 | middleware: RouteMiddleware[],
134 | cb: Handler,
135 | index: number
136 | ) => {
137 | // Our exit point...
138 | if (index === middleware.length) {
139 | // Call the route handler with the modified req and res objects.
140 | // Also handle the promise errors by passing them to the handleErr to save developers from having to manually wrap every handler in try catch.
141 | try {
142 | const handlerResult = cb(req, res, (error) => {
143 | res.setHeader("Connection", "close");
144 | this._handleErr?.(error, req, res);
145 | });
146 |
147 | if (handlerResult && typeof handlerResult.then === "function") {
148 | handlerResult.catch((error) => {
149 | res.setHeader("Connection", "close");
150 | this._handleErr?.(error, req, res);
151 | });
152 | }
153 |
154 | return handlerResult;
155 | } catch (error) {
156 | res.setHeader("Connection", "close");
157 | this._handleErr?.(error, req, res);
158 | }
159 | } else {
160 | middleware[index](
161 | req,
162 | res,
163 | // The next function
164 | (error) => {
165 | // this function only accepts an error argument to be more compatible with NPM modules that are built for express
166 | if (error) {
167 | res.setHeader("Connection", "close");
168 | return this._handleErr?.(error, req, res);
169 | }
170 | runHandler(req, res, middleware, cb, index + 1);
171 | },
172 | // Error handler for a route middleware
173 | (error) => {
174 | res.setHeader("Connection", "close");
175 | this._handleErr?.(error, req, res);
176 | }
177 | );
178 | }
179 | };
180 |
181 | // Run all the middleware functions (beforeEach functions) before we run the corresponding route
182 | const runMiddleware = (
183 | req: CpeakRequest,
184 | res: CpeakResponse,
185 | middleware: Middleware[],
186 | index: number
187 | ) => {
188 | // Our exit point...
189 | if (index === middleware.length) {
190 | const routes = this.routes[req.method?.toLowerCase() || ""];
191 | if (routes && typeof routes[Symbol.iterator] === "function")
192 | for (const route of routes) {
193 | const match = urlWithoutParams?.match(route.regex);
194 |
195 | if (match) {
196 | // Parse the URL variables from the matched route (like /users/:id)
197 | const vars = this.#extractVars(route.path, match);
198 | req.vars = vars;
199 |
200 | return runHandler(req, res, route.middleware, route.cb, 0);
201 | }
202 | }
203 |
204 | // If the requested route dose not exist, return 404
205 | return res
206 | .status(404)
207 | .json({ error: `Cannot ${req.method} ${urlWithoutParams}` });
208 | } else {
209 | middleware[index](req, res, () => {
210 | runMiddleware(req, res, middleware, index + 1);
211 | });
212 | }
213 | };
214 |
215 | runMiddleware(req, res, this.middleware, 0);
216 | });
217 | }
218 |
219 | route(method: string, path: string, ...args: (RouteMiddleware | Handler)[]) {
220 | if (!this.routes[method]) this.routes[method] = [];
221 |
222 | // The last argument should always be our handler
223 | const cb = args.pop() as Handler;
224 |
225 | if (!cb || typeof cb !== "function") {
226 | throw new Error("Route definition must include a handler");
227 | }
228 |
229 | // Rest will be our middleware functions
230 | const middleware = args.flat() as RouteMiddleware[];
231 |
232 | const regex = this.#pathToRegex(path);
233 | this.routes[method].push({ path, regex, middleware, cb });
234 | }
235 |
236 | beforeEach(cb: Middleware) {
237 | this.middleware.push(cb);
238 | }
239 |
240 | handleErr(cb: (err: unknown, req: CpeakRequest, res: CpeakResponse) => void) {
241 | this._handleErr = cb;
242 | }
243 |
244 | listen(port: number, cb?: () => void) {
245 | return this.server.listen(port, cb);
246 | }
247 |
248 | close(cb?: (err?: Error) => void) {
249 | this.server.close(cb);
250 | }
251 |
252 | // ------------------------------
253 | // PRIVATE METHODS:
254 | // ------------------------------
255 | #pathToRegex(path: string) {
256 | const varNames: string[] = [];
257 | const regexString =
258 | "^" +
259 | path.replace(/:\w+/g, (match, offset) => {
260 | varNames.push(match.slice(1));
261 | return "([^/]+)";
262 | }) +
263 | "$";
264 |
265 | const regex = new RegExp(regexString);
266 | return regex;
267 | }
268 |
269 | #extractVars(path: string, match: RegExpMatchArray) {
270 | // Extract url variable values from the matched route
271 | const varNames = (path.match(/:\w+/g) || []).map((varParam) =>
272 | varParam.slice(1)
273 | );
274 | const vars: StringMap = {};
275 | varNames.forEach((name, index) => {
276 | vars[name] = match[index + 1];
277 | });
278 | return vars;
279 | }
280 | }
281 |
282 | // Util functions
283 | export { serveStatic, parseJSON, render };
284 |
285 | export type {
286 | Cpeak,
287 | CpeakRequest,
288 | CpeakResponse,
289 | Next,
290 | HandleErr,
291 | Middleware,
292 | RouteMiddleware,
293 | Handler,
294 | RoutesMap,
295 | } from "./types";
296 |
297 | export default Cpeak;
298 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Cpeak
2 |
3 | [](https://www.npmjs.com/package/cpeak)
4 |
5 | Cpeak is a minimal and fast Node.js framework inspired by Express.js.
6 |
7 | This project is designed to be improved until it's ready for use in complex production applications, aiming to be more performant and minimal than Express.js. This framework is intended for HTTP applications that primarily deal with JSON and file-based message bodies.
8 |
9 | This is an educational project that was started as part of the [Understanding Node.js: Core Concepts](https://www.udemy.com/course/understanding-nodejs-core-concepts/?referralCode=0BC21AC4DD6958AE6A95) course. If you want to learn how to build a framework like this, and get to a point where you can build things like this yourself, check out this course!
10 |
11 | This is the current demo, and the development of the project will begin starting from **September 2025.**
12 |
13 | ## Why Cpeak?
14 |
15 | - **Minimalism**: No unnecessary bloat, with zero dependencies. Just the core essentials you need to build fast and reliable applications.
16 | - **Performance**: Engineered to be fast, **Cpeak** won’t sacrifice speed for excessive customizability.
17 | - **Educational**: Every new change made in the project will be explained in great detail in this [YouTube playlist](https://www.youtube.com/playlist?list=PLCiGw8i6NhvqsA-ZZcChJ0kaHZ3hcIVdY). Follow this project and let's see what it takes to build an industry-leading product!
18 | - **Express.js Compatible**: You can easily refactor from Cpeak to Express.js and vice versa. Many npm packages that work with Express.js will also work with Cpeak.
19 |
20 | ## Table of Contents
21 |
22 | - [Getting Started](#getting-started)
23 | - [Hello World App](#hello-world-app)
24 | - [Documentation](#documentation)
25 | - [Including](#including)
26 | - [Initializing](#initializing)
27 | - [Middleware](#middleware)
28 | - [Route Handling](#route-handling)
29 | - [Route Middleware](#route-middleware)
30 | - [URL Variables & Parameters](#url-variables--parameters)
31 | - [Sending Files](#sending-files)
32 | - [Redirecting](#redirecting)
33 | - [Error Handling](#error-handling)
34 | - [Listening](#listening)
35 | - [Util Functions](#util-functions)
36 | - [serveStatic](#servestatic)
37 | - [parseJSON](#parsejson)
38 | - [render](#render)
39 | - [Complete Example](#complete-example)
40 | - [Versioning Notice](#versioning-notice)
41 |
42 | ## Getting Started
43 |
44 | Ready to dive in? Install **Cpeak** via npm:
45 |
46 | ```bash
47 | npm install cpeak
48 | ```
49 |
50 | Cpeak is a **pure ESM** package, and to use it, your project needs to be an ESM as well. You can learn more about that [here](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c).
51 |
52 | ### Hello World App:
53 |
54 | ```javascript
55 | import cpeak from "cpeak";
56 |
57 | const server = new cpeak();
58 |
59 | server.route("get", "/", (req, res) => {
60 | res.json({ message: "Hi there!" });
61 | });
62 |
63 | server.listen(3000, () => {
64 | console.log("Server has started on port 3000");
65 | });
66 | ```
67 |
68 | ## Documentation
69 |
70 | ### Including
71 |
72 | Include the framework like this:
73 |
74 | ```javascript
75 | import cpeak from "cpeak";
76 | ```
77 |
78 | Because of the minimalistic philosophy, you won’t add unnecessary objects to your memory as soon as you include the framework. If at any point you want to use a particular utility function (like `parseJSON` and `serveStatic`), include it like the line below, and only at that point will it be moved into memory:
79 |
80 | ```javascript
81 | import cpeak, { serveStatic, parseJSON } from "cpeak";
82 | ```
83 |
84 | ### Initializing
85 |
86 | Initialize the Cpeak server like this:
87 |
88 | ```javascript
89 | const server = new cpeak();
90 | ```
91 |
92 | Now you can use this server object to start listening, add route logic, add middleware functions, and handle errors.
93 |
94 | ### Middleware
95 |
96 | If you add a middleware function, that function will run before your route logic kicks in. Here you can customize the request object, return an error, or do anything else you want to do prior to your route logic, like authentication.
97 |
98 | After calling `next`, the next middleware function is going to run if there’s any; otherwise, the route logic is going to run.
99 |
100 | ```javascript
101 | server.beforeEach((req, res, next) => {
102 | if (req.headers.authentication) {
103 | // Your authentication logic...
104 | req.userId = "";
105 | req.custom = "This is some string";
106 | next();
107 | } else {
108 | // Return an error and close the request...
109 | return res.status(401).json({ error: "Unauthorized" });
110 | }
111 | });
112 |
113 | server.beforeEach((req, res, next) => {
114 | console.log(
115 | "The custom value was added from the previous middleware: ",
116 | req.custom
117 | );
118 | next();
119 | });
120 | ```
121 |
122 | ### Route Middleware
123 |
124 | You can also add middleware functions for a particular route handler like this:
125 |
126 | ```javascript
127 | const requireAuth = (req, res, next, handleErr) => {
128 | // Check if user is logged in, if so then:
129 | req.test = "this is a test value";
130 | next();
131 |
132 | // If user is not logged in:
133 | return handleErr({ status: 401, message: "Unauthorized" });
134 | };
135 |
136 | server.route("get", "/profile", requireAuth, (req, res, handleErr) => {
137 | console.log(req.test); // this is a test value
138 | });
139 | ```
140 |
141 | You can add as many middleware functions as you want for a route:
142 |
143 | ```javascript
144 | server.route(
145 | "get",
146 | "/profile",
147 | requireAuth,
148 | anotherFunction,
149 | oneMore,
150 | (req, res, handleErr) => {
151 | // your logic
152 | }
153 | );
154 | ```
155 |
156 | ### Route Handling
157 |
158 | You can add new routes like this:
159 |
160 | ```javascript
161 | server.route("patch", "/the-path-you-want", (req, res) => {
162 | // your route logic
163 | });
164 | ```
165 |
166 | First add the HTTP method name you want to handle, then the path, and finally, the callback. The `req` and `res` object types are the same as in the Node.js HTTP module (`http.IncomingMessage` and `http.ServerResponse`). You can read more about them in the [official Node.js documentation](https://nodejs.org/docs/latest/api/http.html).
167 |
168 | ### URL Variables & Parameters
169 |
170 | Since in HTTP these are called URL parameters: `/path?key1=value1&key2=value2&foo=900`, in Cpeak, we also call them `params` (short for HTTP URL parameters).
171 | We can also do custom path management, and we call them `vars` (short for URL variables).
172 |
173 | Here’s how we can read both:
174 |
175 | ```javascript
176 | // Imagine request URL is example.com/test/my-title/more-text?filter=newest
177 | server.route("patch", "/test/:title/more-text", (req, res) => {
178 | const title = req.vars.title;
179 | const filter = req.params.filter;
180 |
181 | console.log(title); // my-title
182 | console.log(filter); // newest
183 | });
184 | ```
185 |
186 | ### Sending Files
187 |
188 | You can send a file as a Node.js Stream anywhere in your route or middleware logic like this:
189 |
190 | ```javascript
191 | server.route("get", "/testing", (req, res) => {
192 | return res.status(200).sendFile("", "");
193 |
194 | // Example:
195 | // return res.status(200).sendFile("./images/sun.jpeg", "image/jpeg");
196 | });
197 | ```
198 |
199 | The file’s binary content will be in the HTTP response body content. Make sure you specify a correct path relative to your CWD (use the `path` module for better compatibility) and also the correct HTTP MIME type for that file.
200 |
201 | ### Redirecting
202 |
203 | If you want to redirect to a new URL, you can simply do:
204 |
205 | ```javascript
206 | res.redirect("https://whatever.com");
207 | ```
208 |
209 | ### Error Handling
210 |
211 | If anywhere in your route functions or route middleware functions you want to return an error, it's cleaner to pass it to the `handleErr` function like this:
212 |
213 | ```javascript
214 | server.route("get", "/api/document/:title", (req, res, handleErr) => {
215 | const title = req.vars.title;
216 |
217 | if (title.length > 500)
218 | return handleErr({ status: 400, message: "Title too long." });
219 |
220 | // The rest of your logic...
221 | });
222 | ```
223 |
224 | And then handle all the errors like this in the `handleErr` callback:
225 |
226 | ```javascript
227 | server.handleErr((error, req, res) => {
228 | if (error && error.status) {
229 | res.status(error.status).json({ error: error.message });
230 | } else {
231 | // Log the unexpected errors somewhere so you can keep track of them...
232 | console.error(error);
233 | res.status(500).json({
234 | error: "Sorry, something unexpected happened on our side.",
235 | });
236 | }
237 | });
238 | ```
239 |
240 | The error object is the object that you passed to the `handleErr` function earlier in your routes.
241 |
242 | ### Listening
243 |
244 | Start listening on a specific port like this:
245 |
246 | ```javascript
247 | server.listen(3000, () => {
248 | console.log("Server has started on port 3000");
249 | });
250 | ```
251 |
252 | ### Util Functions
253 |
254 | There are utility functions that you can include and use as middleware functions. These are meant to make it easier for you to build HTTP applications. In the future, many more will be added, and you only move them into memory once you include them. No need to have many npm dependencies for simple applications!
255 |
256 | The list of utility functions as of now:
257 |
258 | - serveStatic
259 | - parseJSON
260 | - render
261 |
262 | Including any one of them is done like this:
263 |
264 | ```javascript
265 | import cpeak, { utilName } from "cpeak";
266 | ```
267 |
268 | #### serveStatic
269 |
270 | With this middleware function, you can automatically set a folder in your project to be served by Cpeak. Here’s how to set it up:
271 |
272 | ```javascript
273 | server.beforeEach(
274 | serveStatic("./public", {
275 | mp3: "audio/mpeg",
276 | })
277 | );
278 | ```
279 |
280 | If you have file types in your public folder that are not one of the following, make sure to add the MIME types manually as the second argument in the function as an object where each property key is the file extension, and each value is the correct MIME type for that. You can see all the available MIME types on the [IANA website](https://www.iana.org/assignments/media-types/media-types.xhtml).
281 |
282 | ```
283 | html: "text/html",
284 | css: "text/css",
285 | js: "application/javascript",
286 | jpg: "image/jpeg",
287 | jpeg: "image/jpeg",
288 | png: "image/png",
289 | svg: "image/svg+xml",
290 | txt: "text/plain",
291 | eot: "application/vnd.ms-fontobject",
292 | otf: "font/otf",
293 | ttf: "font/ttf",
294 | woff: "font/woff",
295 | woff2: "font/woff2"
296 | ```
297 |
298 | #### parseJSON
299 |
300 | With this middleware function, you can easily read and send JSON in HTTP message bodies in route and middleware functions. Fire it up like this:
301 |
302 | ```javascript
303 | server.beforeEach(parseJSON);
304 | ```
305 |
306 | Read and send JSON from HTTP messages like this:
307 |
308 | ```javascript
309 | server.route("put", "/api/user", (req, res) => {
310 | // Reading JSON from the HTTP request:
311 | const email = req.body.email;
312 |
313 | // rest of your logic...
314 |
315 | // Sending JSON in the HTTP response:
316 | res.status(201).json({ message: "Something was created..." });
317 | });
318 | ```
319 |
320 | #### render
321 |
322 | With this function you can do server side rendering before sending a file to a client. This can be useful for dynamic customization and search engine optimization.
323 |
324 | First fire it up like this:
325 |
326 | ```javascript
327 | server.beforeEach(render());
328 | ```
329 |
330 | And then for rendering:
331 |
332 | ```javascript
333 | server.route("get", "/", (req, res, next) => {
334 | return res.render(
335 | "./public/index.html",
336 | {
337 | title: "Page title",
338 | name: "Allan",
339 | },
340 | "text/html"
341 | );
342 | });
343 | ```
344 |
345 | You can then inject the variables into your file in {{ variable_name }} like this:
346 |
347 | ```HTML
348 |
349 |
350 | {{ title }}
351 |
352 |
353 | {{ name }}
354 |
355 |
356 | ```
357 |
358 | ## Complete Example
359 |
360 | Here you can see all the features that Cpeak offers, in one small piece of code:
361 |
362 | ```javascript
363 | import cpeak, { serveStatic, parseJSON, render } from "cpeak";
364 |
365 | const server = new cpeak();
366 |
367 | server.beforeEach(
368 | serveStatic("./public", {
369 | mp3: "audio/mpeg",
370 | })
371 | );
372 |
373 | server.beforeEach(render());
374 |
375 | // For parsing JSON bodies
376 | server.beforeEach(parseJSON);
377 |
378 | // Adding custom middleware functions
379 | server.beforeEach((req, res, next) => {
380 | req.custom = "This is some string";
381 | next();
382 | });
383 |
384 | // A middleware function that can be specified to run before some particular routes
385 | const testRouteMiddleware = (req, res, next, handleErr) => {
386 | req.whatever = "some calculated value maybe";
387 |
388 | if (req.vars.test !== "something special") {
389 | return handleErr({ status: 400, message: "an error message" });
390 | }
391 |
392 | next();
393 | };
394 |
395 | // Adding route handlers
396 | server.route("get", "/", (req, res, next) => {
397 | return res.render(
398 | "",
399 | {
400 | test: "some testing value",
401 | number: "2343242",
402 | },
403 | ""
404 | );
405 | });
406 |
407 | server.route("get", "/old-url", testRouteMiddleware, (req, res, next) => {
408 | return res.redirect("/new-url");
409 | });
410 |
411 | server.route(
412 | "get",
413 | "/api/document/:title",
414 | testRouteMiddleware,
415 | (req, res, handleErr) => {
416 | // Reading URL variables
417 | const title = req.vars.title;
418 |
419 | // Reading URL parameters (like /users?filter=active)
420 | const filter = req.params.filter;
421 |
422 | // Reading JSON request body
423 | const anything = req.body.anything;
424 |
425 | // Handling errors
426 | if (anything === "not-expected-thing")
427 | return handleErr({ status: 400, message: "Invalid property." });
428 |
429 | // Sending a JSON response
430 | res.status(200).json({ message: "This is a test response" });
431 | }
432 | );
433 |
434 | // Sending a file response
435 | server.route("get", "/file", (req, res) => {
436 | // Make sure to specify a correct path and MIME type...
437 | res.status(200).sendFile("", "");
438 | });
439 |
440 | // Handle all the errors that could happen in the routes
441 | server.handleErr((error, req, res) => {
442 | if (error && error.status) {
443 | res.status(error.status).json({ error: error.message });
444 | } else {
445 | console.error(error);
446 | res.status(500).json({
447 | error: "Sorry, something unexpected happened from our side.",
448 | });
449 | }
450 | });
451 |
452 | server.listen(3000, () => {
453 | console.log("Server has started on port 3000");
454 | });
455 | ```
456 |
457 | ## Versioning Notice
458 |
459 | #### Version `1.x.x`
460 |
461 | Version `1.x.x` represents the initial release of our framework, developed during the _Understanding Node.js Core Concepts_ course. These versions laid the foundation for our project.
462 |
463 | #### Version `2.x.x`
464 |
465 | All version `2.x.x` releases are considered to be in active development, following the completion of the course. These versions include ongoing feature additions and API changes as we refine the framework. Frequent updates may require code changes, so version `2.x.x` is not recommended for production environments.
466 | For new features, bug fixes, and other changes that don't break existing code, the patch version will be increased. For changes that break existing code, the minor version will be increased.
467 |
468 | #### Version `3.x.x`
469 |
470 | Version `3.x.x` and beyond will be our first production-ready releases. These versions are intended for stable, long-term use, with a focus on backward compatibility and minimal breaking changes.
471 |
--------------------------------------------------------------------------------