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

node-be-utilities

v1.3.0

Published

Backend utilities package by Sanskar

Readme

node-be-utilities

CI Node.js Matrix

A TypeScript backend utilities package by Sanskar.

📚 Documentation

Installation

npm install node-be-utilities

Usage

import {
	greet,
	delay,
	deepClone,
	isEmpty,
	generateRandomString,
	formatDate,
} from 'node-be-utilities';

// Basic greeting
const message = greet('World');
console.log(message); // "Hello, World! Welcome to node-be-utilities."

// Async delay
await delay(1000); // Wait for 1 second

// Deep clone an object
const original = { a: 1, b: { c: 2 } };
const cloned = deepClone(original);

// Check if value is empty
const isEmptyValue = isEmpty(''); // true
const isNotEmpty = isEmpty('hello'); // false

// Generate random string
const randomStr = generateRandomString(8); // e.g., "aB3dEfGh"

Available Scripts

Development

  • npm run dev - Development mode with watch
  • npm run build - Build the TypeScript code to JavaScript
  • npm run build:watch - Build in watch mode
  • npm run clean - Clean the dist directory

Testing

  • npm test - Run tests
  • npm run test:watch - Run tests in watch mode
  • npm run test:coverage - Run tests with coverage
  • npm run test:ci - Run tests in CI mode

Code Quality

  • npm run lint - Run ESLint
  • npm run lint:fix - Fix ESLint errors
  • npm run format - Format code with Prettier
  • npm run format:check - Check code formatting
  • npm run typecheck - Run TypeScript type checking

API Reference

Core

greet(name: string): string

Generate a greeting message with the provided name.


Crypto

uuid(): string

Generate a random UUID (Universally Unique Identifier).

randomText(length?: number): string

Generate a random text string using cryptographic random values. Default length is 4.


Errors

All error classes extend CustomError and can be thrown in Express routes. They automatically set the appropriate HTTP status code and error message.

BadRequestError(message?: string)

HTTP 400 - Bad Request error

UnauthorizedError(message?: string)

HTTP 401 - Unauthorized error

ForbiddenError(message?: string)

HTTP 403 - Forbidden error

NotFoundError(message?: string)

HTTP 404 - Not Found error

MethodNotAllowedError(message?: string)

HTTP 405 - Method Not Allowed error

ConflictError(message?: string)

HTTP 409 - Conflict error

TooManyRequestsError(message?: string)

HTTP 429 - Too Many Requests error

ServerError(message?: string)

HTTP 500 - Internal Server Error

ServiceUnavailableError(message?: string)

HTTP 503 - Service Unavailable error


Logging

error(message: string | object, error: any): void

Logs an error message with context and stack trace to the console in red color.

try {
  // some operation
} catch (err) {
  error('Failed to process request', err);
}

info(message: string | object, data?: any): void

Logs an informational message with optional data and context to the console.

info('User logged in successfully');
info({ action: 'user_login', userId: 123 });

createStore(context: KeyValue): void

Creates an async context store for the current execution context.

getStore(): KeyValue

Retrieves the current async context store.

getStoreValue(key: string): any

Retrieves a specific value from the async context store.


Middleware

createLoggerContext(data?, options?): RequestHandler

Creates an Express middleware that establishes a logging context for each request.

app.use(createLoggerContext({ service: 'api', version: '1.0' }));
app.use(createLoggerContext(
  { service: 'api' },
  { ignoredPaths: ['/health', '/status'] }
));

errorHandler(err, req, res, next): void

Express error handling middleware for CustomError instances. Add at the end of middleware chain.

app.use(errorHandler);

sanitizeQueryId(req, res, next): void

Middleware to validate and sanitize MongoDB ObjectId from request parameters.


Object

filterUndefinedKeys<T>(opt: T): T

Filter out undefined values from an object.

const obj = { a: 1, b: undefined, c: 3 };
const filtered = filterUndefinedKeys(obj); // { a: 1, c: 3 }

Schema (Zod)

idSchema: ZodSchema

Zod schema for validating a single MongoDB ObjectId.

idsArray: ZodSchema

Zod schema for validating an array of MongoDB ObjectIds.


String

capitalize(str: string): string

Capitalize the first letter of a string and lowercase the rest.

toCamelCase(str: string): string

Convert string to camelCase format.

toCamelCase('hello-world'); // 'helloWorld'

toKebabCase(str: string): string

Convert string to kebab-case format.

toKebabCase('helloWorld'); // 'hello-world'

truncate(str: string, length: number, suffix?: string): string

Truncate string to specified length with optional suffix (default: '...').

truncate('Hello World', 8); // 'Hello...'

Validators

idValidator(id: unknown): [boolean, ObjectId | undefined]

Validate and transform a MongoDB ObjectId. Returns a tuple with validation result and transformed ObjectId.

const [isValid, objectId] = idValidator('507f1f77bcf86cd799439011');

Utils

General

getRandomNumber(min: number, max: number): number

Generate a random number between min and max (inclusive).

Delay(seconds: number): Promise<void>

Create a delay for the specified number of seconds.


Date Utilities

getDate(format?: string): string

Get current date in specified format (default: 'YYYY-MM-DD').

getMonth(): string

Get current month as MM format (01-12).

getMonthName(): string

Get current month name in abbreviated format (e.g., 'Jan', 'Feb').

getYear(): string

Get current year in YYYY format.

getMonthYear(format?: string): string

Get current month and year (default: 'YYYY-MM').

toDate(): Date

Get current date as Date object.

dateTime(format?: string): string

Get current date and time (default: 'YYYY-MM-DD HH:mm:ss').

now(): number

Get current time in milliseconds.

format(date: InputDate, format?: string): string

Format a date using the specified format.

getMoment(date: InputDate, format?: string): Moment

Create a moment object from input date.

getMomentNow(): Moment

Get current moment object.

isValid(date: InputDate, format?: string): boolean

Check if a date is valid.

getLocalTime(date?: InputDate, format?: string): string

Get local time from date (converts UTC to local timezone).

isTimeBetween(startTime, endTime, targetTime): boolean

Check if a time falls between two other times.

getBetween(start, end): Moment

Get a random time between two times.

fromUnixTime(unixTime: number): Moment

Convert Unix timestamp to moment object.


File Utilities

moveFile(sourcePath: string, destinationPath: string): Promise<void>

Move a file from source to destination.

deleteFile(filePath: string): Promise<void>

Delete a file.

doesExist(path: string): Promise<boolean>

Check if a file or directory exists.

readFile(filePath: string, encoding?: BufferEncoding): Promise<string>

Read file contents as string.

readFileBuffer(filePath: string): Promise<Buffer>

Read file contents as Buffer.

createFile(filePath: string, content: string | Buffer, encoding?: BufferEncoding): Promise<void>

Create a file with content.

createFileFromStream(filePath: string, stream: Readable): Promise<void>

Create a file from a readable stream.

generateJSONFile(filePath: string, data: unknown, pretty?: boolean): Promise<void>

Generate a JSON file from an object.

getMimeType(filePath: string): string

Get MIME type based on file extension.

getExtension(filePath: string): string

Get file extension from path.

getPath(basePath: string, ...filePath: string[]): object

Get file path components (dir, name, ext, base, osPath).

joinPath(...paths: string[]): string

Join multiple path segments.

downloadFile(url: string, destinationPath: string): Promise<void>

Download a file from URL.

base64ToJPG(base64String: string, outputPath: string): Promise<void>

Convert base64 string to JPG file.

base64ToPDF(base64String: string, outputPath: string): Promise<void>

Convert base64 string to PDF file.

copyFile(sourcePath: string, destinationPath: string): Promise<void>

Copy a file from source to destination.

ensureDir(dirPath: string): Promise<void>

Ensure directory exists (create if it doesn't).

getFileSize(filePath: string): Promise<number>

Get file size in bytes.

getFileStats(filePath: string): Promise<Stats>

Get file stats (size, creation time, modification time, etc.).

listFiles(dirPath: string, recursive?: boolean): Promise<string[]>

List files in a directory.

isFile(path: string): Promise<boolean>

Check if path is a file.

isDirectory(path: string): Promise<boolean>

Check if path is a directory.

fileToBase64(filePath: string): Promise<string>

Get file content as base64 string.

appendToFile(filePath: string, content: string, encoding?: BufferEncoding): Promise<void>

Append content to a file.

watchFile(filePath: string, callback: Function): FSWatcher

Watch a file for changes.

createTempFile(content: string | Buffer, prefix?: string, suffix?: string): Promise<string>

Create a temporary file with content.

cleanupTempFiles(tempDir?: string, maxAge?: number): Promise<number>

Clean up temporary files older than specified age.


Express Utilities

Respond({ res, status, data? }): void

Send a standardized JSON response.

Respond({ res, status: 200, data: { user: {...} } });

RespondFile({ res, filename, filepath?, data? }): void

Send a file as a response with proper headers.

setCookie(res: Response, { key, value, expires }): void

Set a secure HTTP-only cookie.

clearCookie(res: Response, key: string): void

Clear a cookie by setting it to expire immediately.

getRequestIP(req: Request): string

Extract the client IP address from the request.

debugPrint(...args: any[]): void

Print debug information only in non-production environments.