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 🙏

© 2024 – Pkg Stats / Ryan Hefner

quickload

v1.0.4

Published

A simple utility to load json config files.

Downloads

520

Readme

quickload

NPM Package: quickload

Introduction

A robust and type-safe configuration loader for Node.js applications with support for environment-specific configs, validation, and caching. Compatible with both Backend and Frontend environments.

quickload organizes hierarchical configurations for your app deployments by letting you define a set of default parameters and extend them for different deployment environments (development, production, test, etc.).

⚠️ Development Status

This library is under active development. Some features are still being implemented or refined.

Available Features

  • ✅ Environment-specific configuration management
  • ✅ TypeScript support with strict typing
  • ✅ JSON Schema validation using Ajv (Coming soon)
  • ✅ Basic configuration loading
  • ✅ Environment variable support
  • ✅ Multiple environment support (development, production, test, staging)
  • ✅ Configuration caching for performance optimization
  • ✅ Deep merging of configuration objects

Features In Development

  • 🚧 Multiple file format support (YAML)
  • 🚧 Configuration watching and hot reload
  • 🚧 Custom configuration sources
  • 🚧 Secure secrets management

Features

  • ✨ Environment-specific configuration management
  • 🛡️ JSON Schema validation using Ajv
  • 🚀 Configuration caching for performance optimization
  • 🔄 Deep merging of configuration objects
  • ⚡ Async/Promise-based operations
  • 📘 TypeScript support with strict typing
  • 🎯 Comprehensive error handling
  • 🔍 Environment variable interpolation
  • 📁 Multiple file format support (JSON, YAML, JS/TS)
  • 🔒 Secure secrets management
  • 🎨 Custom configuration sources

Installation

# Using npm
npm install quickload

# Using yarn
yarn add quickload

# Using pnpm
pnpm add quickload

Directory Structure

project/
├── config/
│   ├── default/           # Base configuration
│   │   ├── app.json
│   │   └── database.json
│   ├── development/       # Development overrides
│   │   ├── app.json
│   │   └── database.json
│   ├── production/        # Production overrides
│   │   ├── app.json
│   │   └── database.json
│   └── test/             # Test environment overrides
       ├── app.json
       └── database.json

Basic Usage

  1. Define Your Configuration Files
// config/default/app.json
{
  "name": "my-app",
  "port": 3000,
  "logLevel": "info",
  "api": {
    "timeout": 5000,
    "retries": 3
  }
}

// config/default/database.json
{
  "host": "localhost",
  "port": 5432,
  "database": "myapp",
  "pool": {
    "min": 2,
    "max": 10
  }
}

// config/production/database.json
{
  "host": "prod-db.example.com",
  "pool": {
    "max": 20
  }
}
  1. Type-Safe Configuration
// types/config.ts
interface AppConfig {
  name: string;
  port: number;
  logLevel: 'debug' | 'info' | 'warn' | 'error';
  api: {
    timeout: number;
    retries: number;
  };
  database: {
    host: string;
    port: number;
    database: string;
    pool: {
      min: number;
      max: number;
    };
  };
}

// Schema validation
const configSchema = {
  type: 'object',
  properties: {
    name: { type: 'string' },
    port: { type: 'number', minimum: 1024 },
    logLevel: {
      type: 'string',
      enum: ['debug', 'info', 'warn', 'error'],
    },
    api: {
      type: 'object',
      properties: {
        timeout: { type: 'number', minimum: 0 },
        retries: { type: 'number', minimum: 0 },
      },
      required: ['timeout', 'retries'],
    },
    database: {
      type: 'object',
      properties: {
        host: { type: 'string' },
        port: { type: 'number', minimum: 1, maximum: 65535 },
        database: { type: 'string' },
        pool: {
          type: 'object',
          properties: {
            min: { type: 'number', minimum: 0 },
            max: { type: 'number', minimum: 1 },
          },
          required: ['min', 'max'],
        },
      },
      required: ['host', 'port', 'database', 'pool'],
    },
  },
  required: ['name', 'port', 'logLevel', 'api', 'database'],
} as const;
  1. Loading Configuration
import { ConfigLoaderOptions, loadConfig } from 'quickload';

async function initializeConfig(): Promise<AppConfig> {
  const options: ConfigLoaderOptions = {
    schema: configSchema,
    configDir: './config',
    cache: true,
    env: process.env.NODE_ENV || 'development',
    // Optional: Custom environment variable prefix
    envPrefix: 'MYAPP_',
    // Optional: Custom file patterns
    patterns: ['*.json', '*.yaml'],
  };

  try {
    const config = await loadConfig(options);
    return config as AppConfig;
  } catch (error) {
    if (error instanceof ConfigurationError) {
      console.error('Configuration error:', error.message);
      console.error('Validation errors:', error.errors);
    } else {
      console.error('Unexpected error:', error);
    }
    process.exit(1);
  }
}

// Usage in your application
const config = await initializeConfig();
console.log(`Starting ${config.name} on port ${config.port}`);
  1. Environment Variables Override (In Development)

quickload supports environment variable overrides using a specific format:

# Override configuration values using environment variables
MYAPP_PORT=8080
MYAPP_DATABASE__HOST=custom-db.example.com
MYAPP_API__TIMEOUT=10000
  1. Advanced Features

Custom Configuration Sources

import { ConfigSource } from 'quickload';

class RemoteConfigSource implements ConfigSource {
  async load() {
    // Implement remote configuration fetching
    return await fetchRemoteConfig();
  }
}

const options: ConfigLoaderOptions = {
  sources: [
    new FileConfigSource(),
    new RemoteConfigSource(),
    new EnvironmentConfigSource(),
  ],
};

Configuration Watching (In Development)

const config = await loadConfig({
  ...options,
  watch: true,
  onChange: (newConfig) => {
    console.log('Configuration updated:', newConfig);
  },
});

Error Handling

The library provides detailed error information:

try {
  const config = await loadConfig(options);
} catch (error) {
  if (error instanceof ConfigurationError) {
    // Handle validation errors
    error.errors.forEach((err) => {
      console.error(`Validation error at ${err.path}: ${err.message}`);
    });
  } else if (error instanceof FileNotFoundError) {
    console.error('Configuration file not found:', error.path);
  } else {
    console.error('Unexpected error:', error);
  }
}

Known Limitations

  • Hot reload feature is not yet available
  • YAML support is under development

Best Practices

  • Always use TypeScript interfaces for type safety
  • Implement validation schemas for runtime safety
  • Use environment-specific configurations sparingly
  • Keep sensitive information in environment variables
  • Enable caching in production environments
  • Implement proper error handling
  • Use meaningful configuration grouping

Contributing

Contributions are always welcome!

Please follow our contributing guidelines.

Please adhere to this project's CODE_OF_CONDUCT.

Please take a moment to review this document before submitting your first pull request. We also strongly recommend that you check for open issues and pull requests to see if someone else is working on something similar.

📝 License

See LICENSE for more information.

Authors