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

@khni/utils

v1.0.0

Published

@khni/utils is a TypeScript utility library that provides essential functions for Node.js applications.

Downloads

156

Readme

@khni/utils

A lightweight collection of TypeScript utility functions for configuration management, time handling, number operations, and environment variable parsing.

Installation

npm install @khni/utils
pnpm add @khni/utils
yarn add @khni/utils

Features

  • ⚙️ Configuration Management - Type-safe config initialization with logging support
  • Time Utilities - Time string parsing and expiration date generation
  • 🔢 Number Utilities - Random number generation and safe environment variable parsing
  • 🛡️ Type Safety - Full TypeScript support with comprehensive type definitions
  • 📝 Logging Integration - Built-in support for custom loggers

Quick Start

import {
  createConfig,
  generateExpiredDate,
  generateRandomNumber,
  getSafeNumberFromEnv,
  parseTimeString,
} from "@khni/utils";

// Configuration management
interface AppConfig {
  port: number;
  host: string;
  logger?: { info: (msg: string) => void };
}

const config = createConfig<AppConfig>("App");
config.set({ port: 3000, host: "localhost", logger: console });
const settings = config.get(); // throws if not initialized

// Time utilities
const expiryDate = generateExpiredDate("30m"); // Date 30 minutes from now
const timeInfo = parseTimeString("2h"); // { timeValue: 2, timeUnit: 'hours' }

// Number utilities
const random = generateRandomNumber(1, 100); // Random number between 1-100
const port = getSafeNumberFromEnv("PORT", 3000); // Safe env variable parsing

API Reference

Configuration Management

createConfig<T>(name: string)

Creates a type-safe configuration manager with initialization tracking.

interface DatabaseConfig {
  host: string;
  port: number;
  logger?: { info: (msg: string) => void };
}

const dbConfig = createConfig<DatabaseConfig>("Database");

// Initialize configuration (logs to provided logger or console)
dbConfig.set({
  host: "localhost",
  port: 5432,
  logger: console, // Optional custom logger
});

// Retrieve configuration (throws if not initialized)
const config = dbConfig.get();
console.log(config.host); // 'localhost'

Time Utilities

generateExpiredDate(timeString: ValidTimeString): Date

Generates a future date based on a time duration string.

Supported formats:

  • "500ms" - milliseconds
  • "30s" - seconds
  • "10m" - minutes
  • "2h" - hours
  • "7d" - days
// Get dates for various time periods
const in5Minutes = generateExpiredDate("5m");
const in2Hours = generateExpiredDate("2h");
const in1Week = generateExpiredDate("7d");

// Use for token expiration, cache TTL, etc.
const tokenExpiry = generateExpiredDate("1h");

parseTimeString(input: ValidTimeString): { timeValue: number; timeUnit: string }

Parses a time string into its numeric value and human-readable unit with proper pluralization.

const result1 = parseTimeString("10m");
// { timeValue: 10, timeUnit: 'minutes' }

const result2 = parseTimeString("1h");
// { timeValue: 1, timeUnit: 'hour' }

const result3 = parseTimeString("500ms");
// { timeValue: 500, timeUnit: 'milliseconds' }

Number Utilities

generateRandomNumber(min: number, max: number): number

Generates a cryptographically secure random integer between min and max (inclusive).

// Generate various random numbers
const diceRoll = generateRandomNumber(1, 6); // 1-6
const percentage = generateRandomNumber(0, 100); // 0-100
const largeRandom = generateRandomNumber(1000, 9999); // 4-digit code

// Throws error if min > max
generateRandomNumber(10, 5); // Error: Min value cannot be greater than max value

getSafeNumberFromEnv(key: string, fallback: number): number

Safely parses a number from environment variables with fallback support.

// Read from environment with fallbacks
const port = getSafeNumberFromEnv("PORT", 3000);
const maxConnections = getSafeNumberFromEnv("MAX_CONNECTIONS", 100);
const timeout = getSafeNumberFromEnv("TIMEOUT_MS", 5000);

// Handles missing or invalid values gracefully
// process.env.PORT = "8080" -> returns 8080
// process.env.PORT = "invalid" -> returns 3000
// process.env.PORT = undefined -> returns 3000

Type Definitions

Time Units

type TimeUnit = "ms" | "s" | "m" | "h" | "d";
type ValidTimeString = `${number}${TimeUnit}`;

Error Handling

All functions include proper error handling:

  • createConfig().get() throws if config not initialized
  • generateExpiredDate() throws on invalid time format
  • generateRandomNumber() throws if min > max
  • parseTimeString() throws on invalid time string format

Examples

Complete Application Setup

import {
  createConfig,
  getSafeNumberFromEnv,
  generateExpiredDate,
} from "@khni/utils";

interface AppConfig {
  port: number;
  databaseUrl: string;
  sessionTimeout: string;
  logger: { info: (msg: string) => void };
}

// Initialize configuration
const appConfig = createConfig<AppConfig>("App");
appConfig.set({
  port: getSafeNumberFromEnv("PORT", 3000),
  databaseUrl: process.env.DATABASE_URL || "localhost",
  sessionTimeout: "24h",
  logger: console,
});

// Use in your application
const config = appConfig.get();
const sessionExpiry = generateExpiredDate(config.sessionTimeout);

License

MIT