npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@j-o-r/apiserver

v2.1.6

Published

Fast, slim REST API server / socket server

Readme

@j-o-r/apiserver

A lightweight Node.js module for creating HTTP and WebSocket servers with API controllers.

Description

This module provides tools to build HTTP servers that expose API endpoints via controller objects. It includes support for WebSockets, request handling with ClientWrapper, file serving, form parsing, streaming, and more. Built for simplicity and tested with various scenarios.

Version: 2.1.5

Installation

npm install @j-o-r/apiserver

Usage

Import and create a server with a controller object:

import { server } from '@j-o-r/apiserver';

const MyController = {
  index: async (client) => {
    await client.serve(200, { message: 'Hello World' });
  }
};

await server.create('api', { port: 8080, host: '127.0.0.1' }, MyController);
// http://127.0.0.1:8080/api/index

Key Components

  • server.create(name, options, controller): Starts an HTTP server.
    • Options: port (number, default 80), host (string, default 'localhost'), ws (WebSocketServer instance), strict (boolean), verbose (boolean), debug (boolean).
  • server.delete(): Stops the running server gracefully.
  • ClientWrapper (typed as Client): Handles requests with methods for response, data retrieval, etc.
  • WebSocketServer: For WebSocket handling with connection management, messaging, etc.
  • request(url, method, headers, body): Utility for testing requests, supporting various response types.

Examples

HTTP Server

import { server, ClientWrapper } from '@j-o-r/apiserver';

const Controller = {
  echo: async (client) => {
    const data = await client.getPost();
    await client.serve(200, data);
  }
};

await server.create('test', { port: 9022, host: '127.0.0.1' }, Controller);

WebSocket Server

import { WebSocketServer } from '@j-o-r/apiserver';

const ws = new WebSocketServer({
  onMessage: (conn, msg) => { /* handle */ },
  onConnection: (conn) => true
});

// Attach to HTTP server
await server.create('ws', { port: 9022, host: '127.0.0.1', ws }, Controller);

Streaming Response

stream: async (client) => {
  client.writeHeaders(200);
  client.write('[');
  for (let i = 0; i < 10; i++) {
    client.write(JSON.stringify({ id: i }) + (i < 9 ? ',' : ''));
  }
  client.write(']');
  await client.end();
}

API

Server

  • create(namespace, options, app): Starts HTTP server exposing app methods under namespace.
  • delete(): Stops the server.

ClientWrapper (Client)

Methods for handling HTTP requests:

  • serve(status, data, lastModified?): Send JSON response.
  • serveFile(file, mime?): Serve a file.
  • serveFolder(folder, serveData?): Serve a folder (optionally with content).
  • getPost(form?, maxSize?): Get POST data (JSON or form).
  • method(): Get HTTP method.
  • remoteAddress(): Get client IP.
  • parameters(): Get URL parameters.
  • query(): Get query params.
  • id: Getter for unique connection ID.
  • ctime: Getter for creation timestamp.
  • url(): Get request URL path.
  • requestUrl(): Get full request URL.
  • pipe(stream): Pipe stream to response.
  • getRequestHeader(key), getRequestHeaders(): Access incoming headers.
  • addHeader(key, value, override?), deleteHeader(key), getHeader(key): Manage outgoing headers.
  • writeHeaders(status), write(message), end(): Low-level response writing.

WebSocketServer

  • Constructor(options): Options include verbose, pingInterval, pongTimeout, onConnection, onMessage, onClose, onError.
  • initialize(httpServer): Attach to HTTP server.
  • sendToConnection(id, message): Send to specific connection.
  • broadcast(message, filter?): Broadcast to all (or filtered) connections.
  • **getConnections()`: Get all connections.
  • **getConnection(id)`: Get specific connection.
  • closeConnection(id, code?, reason?): Close a connection.
  • **shutdown()`: Shutdown server.

Request Utility

  • request(url, method?, headers?, body?): Make HTTP requests. Returns { status, response, headers, responseType } where responseType is 'none', 'text', 'js', or 'blob'.
  • request.toBlob(formData): Convert FormData to Blob.

See scenarios/ directory for comprehensive examples.

Contributing

Pull requests welcome. Fork and submit.

License

Apache License, Version 2.0