gamatek.http-app v1.0.0-beta.7
Node.js Web Application Framework
This is a simple Node.js web application framework that allows you to create routes and serve static files. It is built using the core Node.js http
module and provides a basic routing mechanism.
const App = require("gamatek.http-app");
const app = new App();
const router = new App.Router();
router.onRequest("GET", "/", (req, res) => {
res.send("Hello World");
});
app.addRouter(router);
app.listen(3000, () => {
console.log("App running on port 3000");
});
Installation
To use this framework in your Node.js application, you can install it via npm:
npm install gamatek.http-app
Features
- Routing: Define routes using HTTP methods (GET, POST, etc. and with ALL) and path patterns.
- Static File Serving: Serve static files (e.g., HTML, CSS, JavaScript) from specified directories.
- Middleware: Easily add custom middleware functions to handle requests.
- Request and Response Utilities: Helper functions for working with request and response objects.
- Cookie Handling: Functions for setting and parsing cookies.
- EJS Templating: Integrate EJS for rendering dynamic HTML templates.
- Error Handling: Basic error handling for 404 and 500 errors.
Usage
Creating Routes
To create routes for your web application, use Router
class providing an optional base URL. The base URL can be used to group related routes under a common path prefix. Here's an example:
const App = require("gamatek.http-app");
const router = new App.Router("/api");
router.onRequest("GET", "/hello", (req, res) => {
res.send("Hello, World!");
});
module.exports = router;
Or:
const App = require("gamatek.http-app");
module.exports = (app) => {
const router = new App.Router("/api");
router.onRequest("GET", "/hello", (req, res) => {
res.send("Hello, World!");
});
app.addRouter(router);
};
Serving Static Files
You can serve static files by adding them to the statics
array in the App
class. Specify the URL path and the local directory where the files are located:
const app = new App();
app.addRouter(router); // Add your router
app.addStatic("/static", `${__dirname}/public`, 60 * 60); // Cache-Control 1h, default: "no-cach"
Rendering Dynamic Templates with EJS
To render dynamic HTML templates, you can use the EJS templating engine. First, make sure you have EJS installed:
npm install ejs
Then, create an EJS template file (e.g., template.ejs
) in a directory of your choice. You can render this template in a route handler like this:
router.onRequest("GET", "/dynamic", (req, res) => {
// Read data or fetch data as needed
const data = {
title: "Dynamic Page",
message: "Welcome to the dynamic page!",
};
// Render the EJS template
res.render("path/to/template.ejs", data);
});
Make sure to customize the EJS template and data according to your application's needs.
Error Handling
Basic error handling for 404 and 500 errors is included. You can customize the error responses in the App
class.
Utilities
This module provides a set of utility functions to assist you in handling and processing HTTP requests and responses. These utilities simplify common tasks when working with web applications.
1. handlerBody(req, onUploadProgress)
This utility function handles the request body asynchronously and returns a Promise that resolves with the request body as a buffer. Example usage:
router.onRequest("POST", "/upload", (req, res) => {
try {
const onUploadProgress = ({ total, loaded, speed, timeRemaining }) => {
console.log(`${(loaded/total*100).toFixed(1)}% ${App.utils.formatBytes(speed, 1)}/s ${App.utils.formatTime(timeRemaining)}`);
};
const body = await App.utils.handlerBody(req, onUploadProgress);
// Process the request body
console.log("Received request body:", body.toString());
// Send a response
res.send("Request body received.");
} catch (err) {
console.error("Error handling request body:", err);
res.sendStatus(500);
};
});
2. getBodyJSON(req)
This utility function parses JSON data from the request body asynchronously and returns a Promise that resolves with the parsed JSON object. Example usage:
router.onRequest("POST", "/upload", (req, res) => {
try {
const data = await getBodyJSON(req);
// Process the JSON data
console.log("Received JSON data:", data);
// Send a JSON response
res.json({ message: "JSON data received", data });
} catch (err) {
console.error("Error parsing JSON data:", err);
res.sendStatus(400); // Bad Request
};
});
Changes log
- 22/11/2023 (
beta5
): Add jsDoc and sass engine
5 months ago
7 months ago
7 months ago
7 months ago
6 months ago
7 months ago
5 months ago
7 months ago
7 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago