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 🙏

© 2026 – Pkg Stats / Ryan Hefner

servscript

v2.3.15

Published

ServScript is a lightweight and configurable Node.js module for handling HTTP requests and serving static files with customizable routing and advanced callbacks.

Readme

ServScript

ServScript is a lightweight and configurable Node.js server navigation module designed to handle HTTP requests and serve static files efficiently.

Features

  • Simple configuration: Easily set up your server with customizable options.
  • File serving: Serve static files from a specified directory.
  • Creating routes: Helps to create routes conveniently.
  • Custom Pages: Define custom routes and associated files.
  • Main page and 404 handling: Specify main page and custom 404 error page.
  • Advanced callbacks: Use advanced and error callbacks for custom behavior.
  • Referer logging: Log the referer URL to track request sources.
  • Free port finder: Automatically find a free port to run the server using portfinder.

Installation

To install ServScript, use npm:

npm install servscript

Usage

Here's a basic example of how to use ServScript in your project:

import { Routing, Routes } from 'servscript';

// Define your pages and other configuration options
const pages = new Routes()
    .set(['pages', 'about.html'])
    .set(['pages', 'contact.html'])
    .getAll();
const mainPage = 'pages/index.html';
const notFoundPage = 'pages/404.html';
const pathToServer = '../../..'; // Project directory

// Create a new Routing instance
const server = new Routing(pages, mainPage, notFoundPage, pathToServer);

// Start the server
server.start(3000, 'localhost', () => {
    console.log('Server is running on http://localhost:3000');
});

Import

You can import the module as follows:

import { Routing, Routes } from 'servscript';

API

Routing

constructor(pages, pagesDirectory, mainPage, notFoundPage, pathToServer, relative, port, host, advCallback, errorCallback)

Creates a new Routing instance.

  • pages: An object where keys are route names and values are the filenames of the associated pages.
  • mainPage: The main page of your application (e.g., index.html).
  • notFoundPage: The custom 404 error page (e.g., 404.html).
  • pathToServer: (Optional) The server directory (default: '../../..').
  • relative: (Optional) If true, paths are resolved relative to the source (default: true).
  • port: (Optional) The port on which the server will run (default: 3000).
  • host: (Optional) The host on which the server will run (default: 'localhost').
  • advCallback: (Optional) A custom advanced callback function.
  • errorCallback: (Optional) A custom error callback function.

Advanced Callback

The advCallback function allows for custom behavior during the request processing. This function receives an object with the following properties:

  • request: The HTTP request object.
  • response: The HTTP response object.
  • address(url, callback): Executes the callback if the request URL matches.
  • stop(): Ends the response without further processing.
  • redirect(url): Redirects to the specified URL.
  • send(path): Sends the specified file or imitated content.
  • imitate(content, type): Returns an object representing imitated content.
  • status(code): Sets the response status code.
  • url: The request URL.
  • resolvePath(file): Resolves the file path relative to the server's directory.
  • path: The resolved file path.
  • source: The referer URL path.
  • query: The query parameters of the request URL.

Example usage of advCallback:

advCallback: async (actions) => {
    actions.address('/custom', async () => {
        actions.send(await actions.resolvePath('pages/custom.html'));
    });
}

Error Callback

The errorCallback function is used to handle errors that occur during request processing. This function receives the following parameters:

  • e: The error object.
  • req: The HTTP request object.
  • res: The HTTP response object.

Example usage of errorCallback:

errorCallback: (e, req, res) => {
    console.error(e);
    res.writeHead(500, {'Content-Type': 'text/plain'});
    res.end(`Server Error: ${e.message}`);
}

start(port, host, callback)

Starts the server.

  • port: (Optional) The port on which the server will run (default: this.port).
  • host: (Optional) The host on which the server will run (default: this.host).
  • callback: (Optional) A callback function to execute after the server starts.

Example:

server.start(3000, 'localhost', () => {
    console.log('Server is running on http://localhost:3000');
});

stop(callback)

Stops the server.

  • callback: (Optional) A callback function to execute after the server stops.

Example:

server.stop(() => {
    console.log('Server has been stopped');
});

set(params)

Sets server parameters.

  • params: An object with keys corresponding to server parameters.

Example:

server.set({
    host: '127.0.0.1',
    port: 8080
});

getPathByUrl(url)

Gets the path of a file based on the URL.

  • url: The URL from which to determine the file path.

Returns the resolved file path.

Example:

const path = server.getPathByUrl('/about');
console.log(path); // Output: Full path to 'about.html'

static createPath(path)

Creates a path from an array of path segments.

  • path: An array of path segments.

Example:

const fullPath = Routing.createPath(['users', '123', 'profile']);
console.log(fullPath); // Output: 'users/123/profile'

static async getFreePort()

Asynchronously finds and returns a free port using portfinder.

Returns a free port as a number.

Example:

const freePort = await Routing.getFreePort();
console.log(`Free port found: ${freePort}`);

Routes

constructor()

Creates a new Routes instance.

getAll()

Returns all routes.

set(path, name)

Creates or rewrites a route.

  • path: Relative path to the file.
  • name: (Optional) The URL of this route.

Returns the updated Routes instance.

Example:

const routes = new Routes()
    .set(['pages', 'about.html'])
    .set(['pages', 'contact.html'])
    .set(['pages', 'index.html'], 'main')
    .getAll();
console.log(routes); // Output: {about: 'pages/about.html', contact: 'pages/contact.html', main: 'index.html'}

getPath(name)

Returns the route path by name as an array.

  • name: Route name.

Example:

const mainRoutePath = new Routes()
    .set(['pages', 'about.html'])
    .set(['pages', 'contact.html'])
    .set(['pages', 'index.html'], 'main')
    .getPath('main');
console.log(mainRoutePath); // Output: ['pages', 'index.html']

getNames(path)

Returns route names by file path.

Example:

const aboutRouteNames = new Routes()
    .set(['pages', 'about.html'])
    .set(['pages', 'about.html'], 'info')
    .set(['pages', 'contact.html'])
    .set(['pages', 'index.html'], 'main')
    .getNames(['pages', 'about.html']);
console.log(aboutRouteNames); // Output: ['about', 'info']

remove(name)

Removes a route by name.

  • name: Route name.

Returns the updated Routes instance.

Example:

const removedInfo = new Routes()
    .set(['pages', 'about.html'])
    .set(['pages', 'about.html'], 'info')
    .set(['pages', 'contact.html'])
    .set(['pages', 'index.html'], 'main')
    .remove('info')
    .getAll();
console.log(removedInfo); // Output: {about: 'pages/about.html', contact: 'pages/contact.html', main: 'pages/index.html'}
  • clear

Removes all routes.

Returns the updated Routes instance.

Example:

const removedAll = new Routes()
    .set(['pages', 'about.html'])
    .set(['pages', 'about.html'], 'info')
    .set(['pages', 'contact.html'])
    .set(['pages', 'index.html'], 'main')
    .clear()
    .getAll();
console.log(removedAll); // Output: {}

When to use

ServScript is particularly useful in the following scenarios:

  1. Development Server:

    • Quickly set up a local development server to serve your static HTML, CSS, and JavaScript files.
  2. Static Site Hosting:

    • Easily host static files or websites over HTTP.
  3. Custom Routing:

    • Define custom routes and associate them with specific files.
  4. Single Page Applications (SPA):

    • Serve the main HTML file and handle 404 errors with a custom error page.
  5. File Serving:

    • Serve various file types.
  6. Custom Server Behavior:

    • Use advanced and error callbacks for custom behavior and error handling.

Running Tests

To run tests, you can simply use the following command:

npm test

Make sure you have a test script defined in your package.json and a test file created with your test cases.

License

This project is licensed under the MIT License.