Numsy is a light-weight TypeScript library for Indian phone number validation, sanitization, and CSV/Excel file processing. Built with class-based architecture, comprehensive error handling, and extensive logging capabilities.*
- π’ Phone Number Validation - Validate Indian mobile numbers (10-digit starting with 6-9)
- π§Ή Smart Sanitization - Clean and normalize phone numbers from various formats
- π File Processing - Parse CSV and Excel files with automatic phone column detection
- π Multiple Number Extraction - Extract multiple phone numbers from text
- π Comprehensive Logging - Built-in logging with configurable log levels
- π‘οΈ Error Handling - Try-catch blocks everywhere with custom error classes
- π― TypeScript Support - Full type definitions included
- β‘ Fast Compilation - Built with SWC for lightning-fast builds
- π§ͺ Well Tested - Comprehensive test coverage
- π¦ Modular Architecture - Use individual components or the unified API
- π¨ Class-Based Design - Modern, maintainable, and extensible
- π Helper Functions - Extensive utility functions for common tasks
npm install numsypnpm add numsyyarn add numsyimport Numsy from 'numsy';
const numsy = new Numsy();
// Validate a phone number
const result = numsy.validate('9876543210');
console.log(result);
// { original: '9876543210', sanitized: '9876543210', isValid: true }
// Check if valid
console.log(numsy.isValid('9876543210')); // true
// Sanitize number
console.log(numsy.sanitize('+91-987-654-3210')); // '9876543210'
// Format with country code
console.log(numsy.format('9876543210', true)); // '+919876543210'import { Parser } from 'numsy';
// or
import parser from 'numsy/parser';
const parser = new Parser();
// Parse CSV file
const result = await parser.parseFile('./contacts.csv');
console.log(result.data);
console.log(result.totalRows);import Numsy from 'numsy';
const numsy = new Numsy();
// Process file with validation
const result = await numsy.processFile('./contacts.csv', './output');
console.log(`Processed ${result.totalRecords} records`);
console.log(`Valid: ${result.validRecords}, Invalid: ${result.invalidRecords}`);Numsy includes a built-in server with a web interface for processing phone numbers without writing code.
After installing the package:
# Using npx (recommended - no installation needed)
npx @numsy/numsy-serve
# Or install globally first
npm install -g @numsy/numsy
numsy-serve
# With custom options
npx @numsy/numsy-serve --port 3000
npx @numsy/numsy-serve --page
npx @numsy/numsy-serve -p 8080 --page
# Display help
npx @numsy/numsy-serve --helpFor local development (in this repository):
# Using pnpm scripts
pnpm run serve
# Or using npm scripts
npm run serve
# Or directly with ts-node
npx ts-node src/cli/server.ts
# With options (requires -- separator)
pnpm run serve -- --port 3000
pnpm run serve -- --page| Option | Alias | Description | Default |
|---|---|---|---|
--port <number> |
-p |
Specify port number (1024-65535) | 3000 |
--page |
-s, --serve |
Serve the HTML utility page | false |
--help |
-h |
Display help message | - |
You can also configure the server using environment variables:
# Set port via environment variable
PORT=3000 npx @numsy/numsy-serve
# Set environment mode
NODE_ENV=production npx @numsy/numsy-serve- β Auto Port Detection - Automatically finds an available port if default is in use
- π CORS Enabled - Works with any frontend application
- π REST API - Access validation endpoints programmatically
- π Health Check - Built-in health check endpoint
- π― Global API Prefix - All endpoints under
/api - π‘οΈ Graceful Shutdown - Handles SIGTERM and SIGINT signals
Once the server is running, you can access:
- Health Check:
http://localhost:3000/api/health - API Base:
http://localhost:3000/api - Utility Page (with
--pageflag):http://localhost:3000
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
Server Started Successfully β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π Server running on: http://localhost:3000
π‘ API endpoint: http://localhost:3000/api
π Health check: http://localhost:3000/api/health
π Utility page: http://localhost:3000
π Environment: development
β‘ Process ID: 12345
Press Ctrl+C to stop the serverimport Numsy from 'numsy';
const numsy = new Numsy();
// Single validation
const result = numsy.validate('9876543210');
// Batch validation
const numbers = ['9876543210', '8123456789', '1234567890'];
const results = numsy.validateBatch(numbers);
// Extract multiple numbers from text
const text = 'Contact me at 9876543210 or 8123456789';
const extracted = numsy.extractMultiple(text);
console.log(extracted.validNumbers); // ['9876543210', '8123456789']import Numsy from 'numsy';
const numsy = new Numsy();
// Parse file
const parsed = await numsy.parseFile('./data.csv');
// Process with validation
const result = await numsy.processFile('./data.csv', './output');
// Write to CSV
await numsy.writeCsv(data, './output/clean-data.csv');import { Parser, PhoneValidator, FileProcessor } from 'numsy';
// Use Parser separately
const parser = new Parser({
normalizeColumns: true,
detectPhoneColumn: true,
});
// Use PhoneValidator separately
const validator = new PhoneValidator({
enableLogging: false,
});
// Use FileProcessor separately
const processor = new FileProcessor({
outputDir: './output',
});import Numsy from 'numsy';
const numsy = new Numsy({
enableLogging: true, // Enable console logging
logLevel: 'debug', // Log level: 'log' | 'error' | 'warn' | 'debug' | 'verbose'
throwOnError: false, // Throw errors vs return error objects
});
// Update options at runtime
numsy.setOptions({ enableLogging: false });Main class providing unified API:
validate(phone: string): PhoneValidationResult- Validate single phone numbervalidateBatch(phones: string[]): PhoneValidationResult[]- Validate multiple numberssanitize(phone: string): string- Clean phone numberisValid(phone: string): boolean- Quick validation checkformat(phone: string, withCountryCode?: boolean): string- Format phone numberextractMultiple(text: string): MultipleNumbersResult- Extract numbers from textparseFile(filePath: string): Promise<FileParseResult>- Parse CSV/Excel fileprocessFile(filePath: string, outputDir?: string): Promise<ProcessingResult>- Process file with validationwriteCsv(data: ParsedDataRow[], outputPath: string): Promise<void>- Write to CSVdetectPhoneColumn(data: ParsedDataRow[]): string | null- Detect phone column
File parsing operations:
parseFile(filePath: string): Promise<FileParseResult>- Parse filewriteCsv(data, outputPath): Promise<void>- Write CSVwriteProcessedFiles(validData, invalidData, validPath, invalidPath): Promise<void>- Write multiple files
Phone validation operations:
validate(phone: string): PhoneValidationResult- Validate numbervalidateBatch(phones: string[]): PhoneValidationResult[]- Batch validationsanitize(phone: string): string- Sanitize numberisValid(phone: string): boolean- Check validityextractMultiple(text: string): MultipleNumbersResult- Extract numbersformat(phone: string, withCountryCode?: boolean): string- Format number
Pure utility functions:
import {
sanitizePhoneNumber,
validatePhoneNumber,
extractPhoneNumbers,
normalizeDataRows,
detectPhoneColumn,
isNonEmptyString,
isValidNumber,
LoggerHelper,
AppError,
} from 'numsy';Numsy follows a modern, class-based architecture:
src/
βββ common/
β βββ interfaces/ # TypeScript interfaces
β βββ functions/ # Pure utility functions
β βββ helpers/ # Helper classes (Logger, Error, File, Validation)
βββ core/
β βββ Numsy.ts # Main class
β βββ Parser.ts # File parser
β βββ PhoneValidator.ts # Phone validator
β βββ FileProcessor.ts # File processor
βββ index.ts # Package entry point# Install dependencies
pnpm install
# Build package
pnpm run build
# Run tests
pnpm test
# Development with auto-reload
pnpm run dev
# Start server (for web interface)
pnpm run start:devpnpm run build- Build with SWC (fast compilation)pnpm run build:nest- Build with Nest CLIpnpm run dev- Development mode with nodemonpnpm run test- Run testspnpm run test:watch- Watch modepnpm run test:cov- Coverage reportpnpm run lint- Lint codepnpm run format- Format code
- Usage Examples - Comprehensive usage examples
- API Documentation - Complete API reference
- Quick Start Guide - Get started quickly
- Publishing Guide - NPM publishing guide
Numsy includes comprehensive test coverage:
# Run all tests
pnpm test
# Watch mode
pnpm test:watch
# Coverage report
pnpm test:covNumsy provides comprehensive error handling:
import { Numsy, AppError } from 'numsy';
try {
const numsy = new Numsy({ throwOnError: true });
const result = await numsy.processFile('./data.csv');
} catch (error) {
if (error instanceof AppError) {
console.error(`Error [${error.code}]: ${error.message}`);
console.error('Details:', error.details);
}
}Full TypeScript support with complete type definitions:
import {
Numsy,
NumsyOptions,
PhoneValidationResult,
MultipleNumbersResult,
ProcessingResult,
FileParseResult,
ParsedDataRow,
} from 'numsy';
const options: NumsyOptions = {
enableLogging: true,
logLevel: 'debug',
throwOnError: false,
};
const numsy = new Numsy(options);
const result: PhoneValidationResult = numsy.validate('9876543210');Contributions are welcome! Please read CONTRIBUTING.md for details.
MIT License - see LICENSE file for details.
If you find this package helpful, please give it a star on GitHub!
- Bundle Size: Optimized and tree-shakeable
- TypeScript: 100% TypeScript codebase
- Test Coverage: Comprehensive test suite
- Dependencies: Minimal and well-maintained
- β‘ SWC Compilation - 20x faster than TypeScript compiler
- π― Tree-Shakeable - Import only what you need
- π¦ Modular Design - Use individual components
- π§ Zero Config - Works out of the box
- π‘οΈ Type Safe - Full TypeScript support
Made with β€οΈ by Shri Kumar Sharma