HttpServer PRO
The HttpServer class provides a lightweight local HTTP server that can handle HTTP requests, serve static files, and manage WebSocket connections. It is commonly used for local debugging, communication between devices, and serving simple web APIs inside scripts.
Overview
HttpServer supports:
- Handling custom HTTP routes with programmable handlers
- Serving static files or directories
- Managing WebSocket connections for real-time communication
- Listening on both IPv4 and IPv6
- Configurable ports (including automatic random ports)
- Server state tracking
Properties
state: HttpServerState
The current state of the server.
port: number | null
The port number the server is listening on.
If the server is not running, this value is null.
isIPv4: boolean
Indicates whether the server is listening on an IPv4 address.
If false, the server may be using IPv6.
listenAddressIPv4: string | null
The IPv4 address to listen on.
Only used when forceIPv4 is set to true.
listenAddressIPv6: string | null
The IPv6 address to listen on.
Only used when forceIPv6 is set to true.
Methods
registerHandler(path: string, handler: (request: HttpRequest) => HttpResponse): void
Registers a handler for a specific request path.
Parameters:
Example:
registerFile(path: string, filePath: string): void
Registers a single static file for a specific path.
Parameters:
Example:
Accessing /readme in the browser returns the file content.
registerFilesFromDirectory(path: string, directory: string, options?: { defaults?: string[] }): void
Registers a directory of static files to serve.
Parameters:
Example:
When accessing /static/, the server automatically serves the default index file.
registerWebsocket(path: string, handlers: WebSocketHandlers): void
Registers a WebSocket handler for the specified path.
Parameters:
WebSocketHandlers type definition:
Example:
start(options?: { port?: number; forceIPv4?: boolean }): string | null
Starts the HTTP server.
Parameters:
Returns:
- Returns
nullif the server starts successfully. - Returns an error message string if the server fails to start.
Example:
stop(): void
Stops the HTTP server and releases its resources.
Example:
Type Definitions
HttpServerState
WebSocketSession
Represents a live WebSocket connection.
Methods:
Full Example
Below is a complete example of a working HTTP + WebSocket server:
