wave.http
v1.0.0
Published
Light HTTP Server
Downloads
60
Readme
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("wave.http");
const app = new App();
const router = new App.Router();
router.on("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 wave.http
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.
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("wave.http");
const router = new App.Router("/api");
router.on("GET", "/hello", (req, res) => {
res.send("Hello, World!");
});
module.exports = router;
Or:
const App = require("wave.http");
module.exports = (app) => {
const router = new App.Router("/api");
router.on("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`, { maxAge: 3600 }); // Cache-Control 1h, default: "no-cache"
Rendering Dynamic Templates with EJS
To render dynamic HTML templates, you can use the EJS templating engine.
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.on("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.
handlerBody(req, options)
This utility function handles the request body asynchronously and returns a Promise that resolves with the request body as a buffer.
Options
parser
: 'text', 'json', 'form-urlencoded': Specifies the format to parse the data into.maxFileSize
: The maximum allowed file size in bytes. If exceeded, the request is aborted.onUploadProgress
: A callback function that receives upload progress updates.
Example usage:
router.on("POST", "/upload", async (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 options = {
parser: 'json',
maxFileSize: 10485760 // 10MB
onUploadProgress,
};
const body = await handlerBody(req, options);
// Process the request body
console.log("Received request body:", body);
// Send a response
res.send("Request body received.");
} catch (err) {
console.error("Error handling request body:", err);
res.sendStatus(500);
}
});
Changes log
17/11/2024
: Publish the first release.