@saffan/devtools-js
v2.0.0
Published
Tiny zero-dependency powerful utilities for Node.js developers - array, math, date, url, cli, system, fs, structures, stream, and crypto utilities
Maintainers
Readme
⚡ @saffan/devtools-js
Tiny zero-dependency utility toolkit for Node.js developers. Stop rewriting the same helpers.
🚀 All-in-one Node developer toolkit
@saffan/devtools-js provides everything Node.js developers need daily in a single, tiny, zero-dependency package.
✨ Features
- ✅ Zero dependencies - Only uses Node.js built-ins
- ✅ Tiny & fast - < 20KB, optimized for performance
- ✅ TypeScript ready - Full type definitions included
- ✅ ES Modules - Modern import/export syntax
- ✅ Production ready - Battle-tested utilities
- ✅ CLI included - Use utilities from command line
- ✅ 10+ Utility Categories - Covering all common development needs
📦 Installation
npm install @saffan/devtools-js
# or
yarn add @saffan/devtools-js
# or
pnpm add @saffan/devtools-js🔧 Quick Start
import {
sleep, retry, uuid, logger,
env, merge, pick, omit,
readJSON, writeJSON, fileExists,
timer, safeTry, asyncQueue,
debounce, throttle, hash,
randomString, deepClone, isEmpty
} from '@saffan/devtools-js';📚 Complete API Reference
1. Array Utilities (@saffan/devtools-js/array)
Comprehensive array manipulation functions for data transformation, filtering, and analysis.
| Function | Description | Example |
|----------|-------------|---------|
| chunk() | Split array into chunks | chunk([1,2,3,4], 2) → [[1,2],[3,4]] |
| flatten() | Flatten nested arrays | flatten([1,[2,[3]]]) → [1,2,3] |
| unique() | Remove duplicates | unique([1,2,2,3]) → [1,2,3] |
| groupBy() | Group by key/function | groupBy(['a','bb','ccc'], 'length') |
| partition() | Split into two groups | partition([1,2,3], x => x % 2) |
| zip() | Combine arrays element-wise | zip([1,2], ['a','b']) → [[1,'a'],[2,'b']] |
| unzip() | Split tuples into arrays | unzip([[1,'a'],[2,'b']]) → [[1,2],['a','b']] |
| intersection() | Find common elements | intersection([1,2,3], [2,3,4]) → [2,3] |
| difference() | Elements in first only | difference([1,2,3], [2,3]) → [1] |
| union() | Unique elements from all | union([1,2], [2,3]) → [1,2,3] |
| sortBy() | Sort by property | sortBy(users, 'age') |
| reverse() | Reverse array | reverse([1,2,3]) → [3,2,1] |
| compact() | Remove falsy values | compact([0,1,false,2,'']) → [1,2] |
| filterNil() | Remove null/undefined | filterNil([1,null,2]) → [1,2] |
| drop() | Remove first n elements | drop([1,2,3,4], 2) → [3,4] |
| take() | Get first n elements | take([1,2,3,4], 2) → [1,2] |
| sliceAfter() | Get elements after match | sliceAfter([1,2,3,4], x => x === 2) → [3,4] |
| sliceBefore() | Get elements before match | sliceBefore([1,2,3,4], x => x === 3) → [1,2] |
| findLast() | Find last matching | findLast([1,2,3,2], x => x === 2) → 2 |
| findIndexLast() | Find last index | findIndexLast([1,2,3,2], x => x === 2) → 3 |
| includes() | Check inclusion | includes([1,2,3], 2) → true |
| indexOfAll() | All indices of value | indexOfAll([1,2,2,3], 2) → [1,2] |
| mapValues() | Map with index | mapValues([1,2,3], (v,i) => v+i) |
| flatMap() | Flatten after map | flatMap([1,2], x => [x,x*2]) → [1,2,2,4] |
| reduceRight() | Reduce right-to-left | reduceRight([1,2,3], (a,b) => a+b, 0) |
| zipWith() | Zip with function | zipWith([[1,2],[3,4]], (a,b) => a+b) |
| sum() | Sum of numbers | sum([1,2,3,4]) → 10 |
| mean() | Average of numbers | mean([1,2,3,4]) → 2.5 |
| min() | Minimum value | min([3,1,4,2]) → 1 |
| max() | Maximum value | max([3,1,4,2]) → 4 |
| range() | Generate range | range(1, 5) → [1,2,3,4,5] |
| repeat() | Repeat array | repeat([1,2], 3) → [1,2,1,2,1,2] |
| isEmpty() | Check if empty | isEmpty([]) → true |
| size() | Get array size | size([1,2,3]) → 3 |
| isArray() | Type guard | isArray([]) → true |
| shuffle() | Random shuffle | shuffle([1,2,3,4]) |
2. Math Utilities (@saffan/devtools-js/math)
Mathematical constants, operations, statistics, and random number generation.
Constants
| Constant | Description | Value |
|----------|-------------|-------|
| PI | Circle constant | 3.14159... |
| E | Euler's number | 2.71828... |
| TAU | 2π (circle constant) | 6.28318... |
| INFINITY | Positive infinity | Infinity |
| NEGATIVE_INFINITY | Negative infinity | -Infinity |
Basic Operations
| Function | Description | Example |
|----------|-------------|---------|
| add() | Add two numbers | add(2, 3) → 5 |
| subtract() | Subtract b from a | subtract(5, 3) → 2 |
| multiply() | Multiply numbers | multiply(4, 5) → 20 |
| divide() | Divide with check | divide(10, 2) → 5 |
| modulo() | Remainder | modulo(10, 3) → 1 |
| power() | Exponentiation | power(2, 3) → 8 |
| sqrt() | Square root | sqrt(16) → 4 |
| root() | nth root | root(8, 3) → 2 |
| factorial() | Factorial (bigint support) | factorial(5) → 120 |
Clamping & Limiting
| Function | Description | Example |
|----------|-------------|---------|
| clamp() | Constrain to range | clamp(15, 0, 10) → 10 |
| mapRange() | Map between ranges | mapRange(50, 0, 100, 0, 1) → 0.5 |
| limit() | Upper bound limit | limit(15, 10) → 10 |
| floor() | Floor to decimals | floor(3.456, 2) → 3.45 |
| ceil() | Ceil to decimals | ceil(3.123, 2) → 3.13 |
| round() | Round to decimals | round(3.456, 2) → 3.46 |
| truncate() | Truncate decimals | truncate(3.456, 2) → 3.45 |
Statistics
| Function | Description | Example |
|----------|-------------|---------|
| sum() | Sum of numbers | sum(1,2,3,4) → 10 |
| product() | Product of numbers | product(2,3,4) → 24 |
| mean() | Arithmetic mean | mean(1,2,3,4) → 2.5 |
| median() | Median value | median(1,3,5) → 3 |
| mode() | Most frequent value | mode(1,2,2,3) → 2 |
| variance() | Statistical variance | variance(1,2,3,4) |
| standardDeviation() | Standard deviation | standardDeviation(1,2,3,4) |
| harmonicMean() | Harmonic mean | harmonicMean(2,4) → 2.67 |
| geometricMean() | Geometric mean | geometricMean(2,4,8) → 4 |
Min/Max & Random
| Function | Description | Example |
|----------|-------------|---------|
| min() | Minimum value | min(1,2,3,4) → 1 |
| max() | Maximum value | max(1,2,3,4) → 4 |
| range() | Max minus min | range(1,2,3,4) → 3 |
| percentile() | pth percentile | percentile([1,2,3,4,5], 90) → 4.5 |
| quantile() | Quantile values | quantile([1,2,3,4,5], 0.5) → 3 |
| random() | Random float 0-1 | random() → 0.456 |
| randomInt() | Random integer | randomInt(1, 100) → 42 |
| randomFloat() | Random float in range | randomFloat(1.5, 3.5) |
| randomBool() | Random boolean | randomBool() → true/false |
| randomItem() | Random array item | randomItem([1,2,3]) → 2 |
| shuffle() | Fisher-Yates shuffle | shuffle([1,2,3,4]) |
| weightedRandom() | Weighted selection | weightedRandom([{v:1,w:1},{v:2,w:3}]) |
| gaussianRandom() | Normal distribution | gaussianRandom() |
| randomString() | Random alphanumeric | randomString(16) |
| randomBytes() | Random bytes | randomBytes(32) |
Number Theory
| Function | Description | Example |
|----------|-------------|---------|
| gcd() | Greatest common divisor | gcd(12, 18) → 6 |
| lcm() | Least common multiple | lcm(4, 6) → 12 |
| isEven() | Check even | isEven(4) → true |
| isOdd() | Check odd | isOdd(4) → false |
| isPrime() | Check prime | isPrime(17) → true |
| isPerfectSquare() | Check square number | isPerfectSquare(16) → true |
| isPowerOfTwo() | Check power of 2 | isPowerOfTwo(8) → true |
| nextPowerOfTwo() | Next power of 2 | nextPowerOfTwo(10) → 16 |
| primeFactors() | Prime factorization | primeFactors(12) → [2,2,3] |
Trigonometry
| Function | Description | Example |
|----------|-------------|---------|
| degToRad() | Degrees to radians | degToRad(180) → π |
| radToDeg() | Radians to degrees | radToDeg(π) → 180 |
| sin() | Sine | sin(Math.PI/2) → 1 |
| cos() | Cosine | cos(0) → 1 |
| tan() | Tangent | tan(0) → 0 |
| asin() | Arc sine | asin(1) → π/2 |
| acos() | Arc cosine | acos(1) → 0 |
| atan() | Arc tangent | atan(1) → π/4 |
| atan2() | Arc tangent 2 | atan2(1, 1) → π/4 |
Formatting
| Function | Description | Example |
|----------|-------------|---------|
| formatNumber() | Format with options | formatNumber(1234.567, 2) |
| formatCurrency() | Format as currency | formatCurrency(1234.56, 'USD') |
| formatPercent() | Format as percent | formatPercent(0.4567) |
| formatCompact() | Compact notation | formatCompact(1500000) → '1.5M' |
| formatBytes() | Format bytes | formatBytes(1048576) → '1 MB' |
3. Date Utilities (@saffan/devtools-js/date)
Comprehensive date manipulation, comparison, formatting, and timezone handling.
Date Creation
| Function | Description | Example |
|----------|-------------|---------|
| now() | Current date | now() |
| unix() | Unix timestamp (seconds) | unix() |
| unixMs() | Unix timestamp (ms) | unixMs() |
| create() | Create from components | create(2024, 0, 15, 10, 30) |
| fromUnix() | From Unix timestamp | fromUnix(1705315200) |
| fromIso() | From ISO string | fromIso('2024-01-15') |
| fromFormat() | From custom format | fromFormat('15/01/2024', 'DD/MM/YYYY') |
Addition/Subtraction
| Function | Description | Example |
|----------|-------------|---------|
| addDays() | Add days | addDays(now(), 7) |
| subDays() | Subtract days | subDays(now(), 3) |
| addHours() | Add hours | addHours(now(), 2) |
| subHours() | Subtract hours | subHours(now(), 1) |
| addMinutes() | Add minutes | addMinutes(now(), 30) |
| subMinutes() | Subtract minutes | subMinutes(now(), 15) |
| addSeconds() | Add seconds | addSeconds(now(), 60) |
| subSeconds() | Subtract seconds | subSeconds(now(), 30) |
| addMonths() | Add months | addMonths(now(), 1) |
| subMonths() | Subtract months | subMonths(now(), 6) |
| addYears() | Add years | addYears(now(), 1) |
| subYears() | Subtract years | subYears(now(), 5) |
Start/End
| Function | Description | Example |
|----------|-------------|---------|
| startOfDay() | Beginning of day | startOfDay(now()) |
| endOfDay() | End of day | endOfDay(now()) |
| startOfWeek() | Start of week | startOfWeek(now()) |
| endOfWeek() | End of week | endOfWeek(now()) |
| startOfMonth() | Start of month | startOfMonth(now()) |
| endOfMonth() | End of month | endOfMonth(now()) |
| startOfQuarter() | Start of quarter | startOfQuarter(now()) |
| endOfQuarter() | End of quarter | endOfQuarter(now()) |
| startOfYear() | Start of year | startOfYear(now()) |
| endOfYear() | End of year | endOfYear(now()) |
Comparison
| Function | Description | Example |
|----------|-------------|---------|
| isSameDay() | Same day? | isSameDay(d1, d2) |
| isSameMonth() | Same month? | isSameMonth(d1, d2) |
| isSameYear() | Same year? | isSameYear(d1, d2) |
| isBefore() | d1 before d2? | isBefore(d1, d2) |
| isAfter() | d1 after d2? | isAfter(d1, d2) |
| isBetween() | In range? | isBetween(d, start, end) |
| isToday() | Is today? | isToday(date) |
| isYesterday() | Is yesterday? | isYesterday(date) |
| isTomorrow() | Is tomorrow? | isTomorrow(date) |
| isPast() | In past? | isPast(date) |
| isFuture() | In future? | isFuture(date) |
| isLeapYear() | Leap year? | isLeapYear(date) |
| isValid() | Valid date? | isValid(date) |
Difference
| Function | Description | Example |
|----------|-------------|---------|
| diffMs() | Difference in ms | diffMs(d1, d2) |
| diffSeconds() | Difference in seconds | diffSeconds(d1, d2) |
| diffMinutes() | Difference in minutes | diffMinutes(d1, d2) |
| diffHours() | Difference in hours | diffHours(d1, d2) |
| diffDays() | Difference in days | diffDays(d1, d2) |
| diffWeeks() | Difference in weeks | diffWeeks(d1, d2) |
| diffMonths() | Difference in months | diffMonths(d1, d2) |
| diffYears() | Difference in years | diffYears(d1, d2) |
Formatting
| Function | Description | Example |
|----------|-------------|---------|
| format() | Custom format | format(date, 'YYYY-MM-DD') |
| formatIso() | ISO string | formatIso(date) |
| formatDate() | YYYY-MM-DD | formatDate(date) |
| formatTime() | HH:mm:ss | formatTime(date) |
| formatDateTime() | Full datetime | formatDateTime(date) |
| formatRelative() | Relative time | formatRelative(date) |
| formatLocale() | Locale-aware | formatLocale(date, 'fr-FR') |
| timeAgo() | "2 hours ago" | timeAgo(date) |
| timeUntil() | "in 3 days" | timeUntil(date) |
Components
| Function | Description | Example |
|----------|-------------|---------|
| getYear() | Get year | getYear(date) |
| getMonth() | Get month (0-11) | getMonth(date) |
| getDay() | Get day (1-31) | getDay(date) |
| getDayOfWeek() | Day of week (0-6) | getDayOfWeek(date) |
| getDayOfYear() | Day of year | getDayOfYear(date) |
| getHour() | Get hour (0-23) | getHour(date) |
| getMinute() | Get minute (0-59) | getMinute(date) |
| getSecond() | Get second (0-59) | getSecond(date) |
| getMillisecond() | Get milliseconds | getMillisecond(date) |
| getQuarter() | Get quarter (1-4) | getQuarter(date) |
| getWeek() | ISO week number | getWeek(date) |
| getDaysInMonth() | Days in month | getDaysInMonth(date) |
| getDaysInYear() | Days in year | getDaysInYear(date) |
| toUnixTimestamp() | Unix timestamp | toUnixTimestamp(date) |
Setting
| Function | Description | Example |
|----------|-------------|---------|
| setYear() | Set year | setYear(date, 2025) |
| setMonth() | Set month | setMonth(date, 5) |
| setDay() | Set day | setDay(date, 15) |
| setHour() | Set hour | setHour(date, 12) |
| setMinute() | Set minute | setMinute(date, 30) |
| setSecond() | Set second | setSecond(date, 0) |
4. URL Utilities (@saffan/devtools-js/url)
URL parsing, manipulation, validation, and encoding for web development.
Parsing
| Function | Description | Example |
|----------|-------------|---------|
| parse() | Parse all components | parse('https://example.com/path') |
| getProtocol() | Get protocol | getProtocol(url) |
| getDomain() | Get main domain | getDomain('https://sub.example.com') |
| getHostname() | Get full hostname | getHostname(url) |
| getPort() | Get port | getPort(url) |
| getPath() | Get pathname | getPath(url) |
| getQuery() | Get query string | getQuery(url) |
| getQueryParams() | Get params object | getQueryParams(url) |
| getHash() | Get hash | getHash(url) |
| getSearch() | Get search string | getSearch(url) |
| getOrigin() | Get origin | getOrigin(url) |
| getHref() | Get full URL | getHref(url) |
Query String
| Function | Description | Example |
|----------|-------------|---------|
| addQueryParam() | Add/update param | addQueryParam(url, 'page', 2) |
| addQueryParams() | Add/update multiple | addQueryParams(url, {page:1,limit:10}) |
| removeQueryParam() | Remove param | removeQueryParam(url, 'page') |
| removeQueryParams() | Remove multiple | removeQueryParams(url, ['page','limit']) |
| getQueryParam() | Get single param | getQueryParam(url, 'id') |
| hasQueryParam() | Check param exists | hasQueryParam(url, 'id') |
| buildQuery() | Build query string | buildQuery({a:1,b:2}) |
| parseQuery() | Parse query string | parseQuery('a=1&b=2') |
Validation
| Function | Description | Example |
|----------|-------------|---------|
| isValidUrl() | Valid URL? | isValidUrl(str) |
| isAbsoluteUrl() | Absolute URL? | isAbsoluteUrl(url) |
| isRelativeUrl() | Relative URL? | isRelativeUrl(url) |
| isSameOrigin() | Same origin? | isSameOrigin(url1, url2) |
| isSubdomain() | Is subdomain? | isSubdomain('sub.example.com', 'example.com') |
| isInternalLink() | Internal link? | isInternalLink(url, base) |
| isExternalLink() | External link? | isExternalLink(url, base) |
| isSecure() | HTTPS? | isSecure(url) |
| isHttp() | HTTP? | isHttp(url) |
| isDataUrl() | Data URL? | isDataUrl(url) |
| isMailto() | Mailto link? | isMailto(url) |
| isTel() | Tel link? | isTel(url) |
| isBlobUrl() | Blob URL? | isBlobUrl(url) |
Resolution
| Function | Description | Example |
|----------|-------------|---------|
| resolveUrl() | Resolve relative | resolveUrl(base, relative) |
| normalizeUrl() | Normalize URL | normalizeUrl(url) |
| resolvePath() | Resolve path | resolvePath(base, relative) |
| joinPath() | Join paths | joinPath('a', 'b', 'c') |
| basename() | Get filename | basename('/path/to/file.txt') |
| dirname() | Get directory | dirname('/path/to/file.txt') |
| extname() | Get extension | extname('/path/to/file.txt') |
| resolve() | Resolve absolute | resolve(base, 'path') |
| relative() | Get relative path | relative(from, to) |
Encoding
| Function | Description | Example |
|----------|-------------|---------|
| encodeURI() | Encode URI | encodeURI(str) |
| decodeURI() | Decode URI | decodeURI(str) |
| encodeURIComponent() | Encode component | encodeURIComponent(str) |
| decodeURIComponent() | Decode component | decodeURIComponent(str) |
| encodeSpecialChars() | HTML encode | encodeSpecialChars('<div>') |
| decodeSpecialChars() | HTML decode | decodeSpecialChars('<div>') |
Formatting
| Function | Description | Example |
|----------|-------------|---------|
| buildUrl() | Build URL | buildUrl('https', 'example.com', '/api') |
| buildSecureUrl() | Build HTTPS URL | buildSecureUrl('example.com', '/api') |
| withProtocol() | Change protocol | withProtocol(url, 'https') |
| withHost() | Change host | withHost(url, 'new.com') |
| withPort() | Change port | withPort(url, 8080) |
| withPath() | Change path | withPath(url, '/new/path') |
| withQuery() | Set query | withQuery(url, 'a=1') |
| withHash() | Set hash | withHash(url, 'section') |
5. CLI Utilities (@saffan/devtools-js/cli)
Command-line interface tools for building CLIs, argument parsing, and interactive prompts.
Argument Parsing
| Function | Description | Example |
|----------|-------------|---------|
| getArgs() | Get all args | getArgs() |
| getFlags() | Parse flags | getFlags() |
| parseArgs() | Parse with options | parseArgs(args, options) |
| parseFlags() | Parse flags only | parseFlags(args) |
| getFirstArg() | First non-flag arg | getFirstArg() |
| getLastArg() | Last non-flag arg | getLastArg() |
| hasFlag() | Check flag exists | hasFlag(args, 'verbose') |
| getFlagValue() | Get flag value | getFlagValue(args, 'port') |
| removeFlag() | Remove flag | removeFlag(args, 'verbose') |
| extractFlags() | Extract all flags | extractFlags(args) |
| extractOptions() | Extract positional | extractOptions(args) |
Command Execution
| Function | Description | Example |
|----------|-------------|---------|
| exec() | Execute sync | exec('ls -la') |
| execAsync() | Execute async | execAsync('npm run build') |
| spawn() | Spawn process | spawn('npm', ['run','build']) |
| spawnAsync() | Spawn async | spawnAsync('npm', ['install']) |
| runScript() | Run Node script | runScript('./build.js') |
| runCommand() | Run in directory | runCommand('npm test', '/project') |
Interactive Prompts
| Function | Description | Example |
|----------|-------------|---------|
| prompt() | Get user input | await prompt('Name?') |
| confirm() | Yes/no confirm | await confirm('Delete?') |
| select() | Select option | await select('Color?', options) |
| checkbox() | Multi-select | await checkbox('Items?', options) |
| password() | Hidden input | await password('Password:') |
| editor() | Open editor | await editor('Message:') |
| list() | List input | await list('Tags:', ',') |
| expand() | Expand/collapse | await expand('View:', options) |
Output & Display
| Function | Description | Example |
|----------|-------------|---------|
| print() | Print message | print('text', {newline:false}) |
| println() | Print line | println('Hello') |
| log() | Log with level | log('message', 'info') |
| success() | Success message | success('Done!') |
| error() | Error message | error('Failed!') |
| warn() | Warning | warn('Check...') |
| info() | Info message | info('Starting...') |
| debug() | Debug message | debug('var:', value) |
| table() | Display table | table(data, columns) |
| tree() | Display tree | tree(data) |
| progress() | Show progress | progress(50, 100) |
| spinner() | Show spinner | spinner('Loading...') |
Colors & Styling
| Function | Description | Example |
|----------|-------------|---------|
| color() | Apply color | color('text', 'red') |
| bgColor() | Background color | bgColor('text', 'blue') |
| bold() | Bold text | bold('text') |
| italic() | Italic text | italic('text') |
| underline() | Underline | underline('text') |
Progress & Loading
| Function | Description | Example |
|----------|-------------|---------|
| createProgressBar() | Create progress bar | createProgressBar(options) |
| createMultiBar() | Create multi-bar | createMultiBar() |
| createSpinner() | Create spinner | createSpinner(options) |
CLI Utilities
| Function | Description | Example |
|----------|-------------|---------|
| getCliName() | Get CLI name | getCliName() |
| getCliVersion() | Get version | getCliVersion() |
| getCliArgs() | Get CLI args | getCliArgs() |
| isInteractive() | TTY interactive? | isInteractive() |
| isCI() | CI environment? | isCI() |
| getTerminalSize() | Terminal size | getTerminalSize() |
6. System Utilities (@saffan/devtools-js/system)
Node.js system utilities for process management, port handling, and system information.
Port Management
| Function | Description | Example |
|----------|-------------|---------|
| getFreePort() | Get random free port | getFreePort() |
| getFreePortRange() | Get port range | getFreePortRange(3000, 5) |
| isPortInUse() | Check port status | await isPortInUse(3000) |
| checkPort() | Detailed check | await checkPort(3000) |
| waitForPort() | Wait for availability | await waitForPort(3000) |
| killPort() | Kill process on port | await killPort(3000) |
| getPortPid() | Get PID using port | await getPortPid(3000) |
| allocatePort() | Allocate preferred port | await allocatePort(3000) |
Process Information
| Function | Description | Example |
|----------|-------------|---------|
| getProcessId() | Get current PID | getProcessId() |
| getProcessInfo() | Get process details | getProcessInfo() |
| getProcessUptime() | Get uptime | getProcessUptime() |
| getProcessMemoryUsage() | Memory usage | getProcessMemoryUsage() |
| getProcessCpuUsage() | CPU usage | getProcessCpuUsage() |
System Information
| Function | Description | Example |
|----------|-------------|---------|
| getOsInfo() | Get OS info | getOsInfo() |
| getOsPlatform() | Get platform | getOsPlatform() |
| getOsArch() | Get architecture | getOsArch() |
| getOsVersion() | Get OS version | getOsVersion() |
| getOsHostname() | Get hostname | getOsHostname() |
| getOsTotalMem() | Total memory | getOsTotalMem() |
| getOsFreeMem() | Free memory | getOsFreeMem() |
| getOsCpus() | CPU info | getOsCpus() |
| getOsUserInfo() | User info | getOsUserInfo() |
| getOsLoadAvg() | Load averages | getOsLoadAvg() |
Memory Management
| Function | Description | Example |
|----------|-------------|---------|
| getMemoryUsage() | Process memory | getMemoryUsage() |
| getHeapUsed() | Heap used | getHeapUsed() |
| getHeapTotal() | Heap total | getHeapTotal() |
| forceGc() | Force GC | forceGc() |
| monitorMemory() | Monitor memory | monitorMemory() |
CPU Management
| Function | Description | Example |
|----------|-------------|---------|
| getCpuUsage() | CPU usage | getCpuUsage() |
| getCpuInfo() | CPU info | getCpuInfo() |
| getCpuCount() | CPU core count | getCpuCount() |
| monitorCpu() | Monitor CPU | monitorCpu() |
7. File System Utilities (@saffan/devtools-js/fs)
Comprehensive file operations including reading, writing, directory management, and file utilities.
File Reading
| Function | Description | Example |
|----------|-------------|---------|
| readFile() | Read file async | await readFile('file.txt') |
| readFileSync() | Read file sync | readFileSync('file.txt') |
| readBuffer() | Read as buffer | await readBuffer('file.bin') |
| readJson() | Read JSON | await readJson('config.json') |
| readJsonSync() | Read JSON sync | readJsonSync('config.json') |
| readYaml() | Read YAML | await readYaml('config.yaml') |
| readCsv() | Read CSV | await readCsv('data.csv') |
| readLines() | Read line by line | for await (const line of readLines(file)) |
| readStdin() | Read stdin | await readStdin() |
File Writing
| Function | Description | Example |
|----------|-------------|---------|
| writeFile() | Write file async | await writeFile('file.txt', content) |
| writeFileSync() | Write file sync | writeFileSync('file.txt', content) |
| writeJson() | Write JSON | await writeJson('config.json', data) |
| writeJsonSync() | Write JSON sync | writeJsonSync('config.json', data) |
| writeCsv() | Write CSV | await writeCsv('data.csv', rows) |
| appendFile() | Append file async | await appendFile('log.txt', line) |
File Operations
| Function | Description | Example |
|----------|-------------|---------|
| copyFile() | Copy file | await copyFile('src', 'dest') |
| moveFile() | Move file | await moveFile('src', 'dest') |
| deleteFile() | Delete file | await deleteFile('file.txt') |
| truncateFile() | Truncate file | await truncateFile('file.txt', 100) |
Directory Operations
| Function | Description | Example |
|----------|-------------|---------|
| createDir() | Create directory | await createDir('mydir') |
| createDirAll() | Create nested dir | await createDirAll('a/b/c') |
| readDir() | Read directory | await readDir('mydir') |
| readDirRecursive() | Recursive read | await readDirRecursive('dir') |
| walkDir() | Walk directory | for await (const entry of walkDir('dir')) |
| deleteDir() | Delete directory | await deleteDir('mydir') |
| deleteDirAll() | Delete recursive | await deleteDirAll('dir') |
| copyDir() | Copy directory | await copyDir('src', 'dest') |
Path Operations
| Function | Description | Example |
|----------|-------------|---------|
| exists() | Check exists | await exists('file.txt') |
| existsSync() | Check exists sync | existsSync('file.txt') |
| isFile() | Is file? | isFile('path') |
| isDirectory() | Is directory? | isDirectory('path') |
| isSymlink() | Is symlink? | isSymlink('path') |
File Information
| Function | Description | Example |
|----------|-------------|---------|
| getFileInfo() | Get file info | await getFileInfo('file.txt') |
| getFileSize() | Get size | getFileSize('file.txt') |
| getFileHash() | Get hash | await getFileHash('file.txt') |
8. Data Structures (@saffan/devtools-js/structures)
High-performance data structures for common programming patterns.
| Class | Description | Use Case |
|-------|-------------|----------|
| LRUCache | LRU Cache with TTL | Cache with size limits |
| RateLimiter | Token bucket rate limiter | API rate limiting |
| TokenBucket | Token bucket algorithm | Rate limiting |
| PriorityQueue | Priority queue | Scheduling, Dijkstra |
| Deque | Double-ended queue | Sliding windows |
| Stack | LIFO stack | Undo/redo |
| Queue | FIFO queue | Task processing |
| Heap | Binary heap | Heap sort, priority |
| MinHeap | Min-heap | Find min efficiently |
| MaxHeap | Max-heap | Find max efficiently |
| BloomFilter | Probabilistic filter | Set membership |
| Trie | Prefix tree | Autocomplete |
| Graph | Undirected graph | Relationships |
| DirectedGraph | Directed graph | DAGs, workflows |
| DisjointSet | Union-find | Connected components |
| BitSet | Bit array | Flags, sets |
9. Stream Utilities (@saffan/devtools-js/stream)
Node.js stream manipulation, conversion, and transformation utilities.
Stream Conversion
| Function | Description | Example |
|----------|-------------|---------|
| streamToBuffer() | Stream to buffer | await streamToBuffer(stream) |
| bufferToStream() | Buffer to stream | bufferToStream(buffer) |
| streamToJson() | Stream to JSON | await streamToJson(stream) |
| streamToString() | Stream to string | await streamToString(stream) |
| stringToStream() | String to stream | stringToStream('text') |
| streamToLines() | Stream to lines | await streamToLines(stream) |
| streamToArray() | Stream to array | await streamToArray(stream) |
Stream Creation
| Function | Description | Example |
|----------|-------------|---------|
| createReadStream() | Create read stream | createReadStream('file.txt') |
| createWriteStream() | Create write stream | createWriteStream('file.txt') |
| createTransformStream() | Create transform | createTransformStream(fn) |
| createPassThroughStream() | Pass-through | createPassThroughStream() |
Stream Manipulation
| Function | Description | Example |
|----------|-------------|---------|
| concatenateStreams() | Concatenate | concatenateStreams(s1, s2) |
| mergeStreams() | Merge streams | mergeStreams(s1, s2) |
| zipStreams() | Zip streams | zipStreams(s1, s2) |
| filterStream() | Filter stream | filterStream(stream, fn) |
| mapStream() | Map stream | mapStream(stream, fn) |
Stream Progress
| Function | Description | Example |
|----------|-------------|---------|
| progressStream() | Progress tracking | progressStream(stream, total) |
| createProgressListener() | Progress listener | `createProgressListener()`` |
Buffering
| Function | Description | Example |
|----------|-------------|---------|
| bufferStream() | Buffer stream | bufferStream(stream, size) |
| batchStream() | Batch items | batchStream(stream, batchSize) |
Compression
| Function | Description | Example |
|----------|-------------|---------|
| createGzipStream() | Gzip compress | createGzipStream() |
| createGunzipStream() | Gzip decompress | createGunzipStream() |
| createBrotliCompressStream() | Brotli compress | createBrotliCompressStream() |
10. Crypto Utilities (@saffan/devtools-js/crypto)
Cryptographic operations including hashing, encryption, and secure random generation.
Hashing
| Function | Description | Example |
|----------|-------------|---------|
| hash() | Hash data | hash('data', 'sha256') |
| hashFile() | Hash file | await hashFile('file.txt') |
| hashSync() | Hash sync | hashSync('data') |
| hmac() | Create HMAC | hmac('data', 'key') |
| hashPassword() | Hash password | hashPassword('pass') |
| verifyPassword() | Verify password | verifyPassword('pass', hash, salt) |
| scrypt() | Scrypt KDF | scrypt('pass', salt, 64) |
Encryption
| Function | Description | Example |
|----------|-------------|---------|
| encrypt() | Encrypt with password | encrypt('data', 'pass') |
| decrypt() | Decrypt with password | decrypt(encrypted, 'pass', iv, salt) |
| encryptWithKey() | Encrypt with key | encryptWithKey(data, key, iv) |
| decryptWithKey() | Decrypt with key | decryptWithKey(data, key, iv) |
| generateKey() | Generate key | generateKey('aes-256-cbc') |
| generateIv() | Generate IV | generateIv('aes-256-cbc') |
| deriveKey() | Derive key | deriveKey('pass', salt) |
Asymmetric Encryption
| Function | Description | Example |
|----------|-------------|---------|
| rsaEncrypt() | RSA encrypt | rsaEncrypt(data, publicKey) |
| rsaDecrypt() | RSA decrypt | rsaDecrypt(data, privateKey) |
| rsaSign() | RSA sign | rsaSign(data, privateKey) |
| rsaVerify() | RSA verify | rsaVerify(data, signature, publicKey) |
| ecGenerateKeyPair() | EC key pair | ecGenerateKeyPair() |
Encoding
| Function | Description | Example |
|----------|-------------|---------|
| toBase64() | To Base64 | toBase64(data) |
| fromBase64() | From Base64 | fromBase64(str) |
| toHex() | To hex | toHex(data) |
| fromHex() | From hex | fromHex(str) |
| toBase64Url() | URL-safe Base64 | toBase64Url(data) |
Random Generation
| Function | Description | Example |
|----------|-------------|---------|
| randomBytes() | Random bytes | randomBytes(32) |
| randomString() | Random string | randomString(16) |
| randomInt() | Random int | randomInt(0, 100) |
| randomUuid() | UUID v4 | randomUuid() |
11. Async Utilities (@saffan/devtools-js/async)
Advanced async patterns including retry, concurrency control, and timeouts.
| Function | Description | Example |
|----------|-------------|---------|
| sleep() | Pause execution | await sleep(1000) |
| retry() | Retry with backoff | await retry(fn, options) |
| asyncQueue() | Concurrency limit | await asyncQueue(tasks, 3) |
| safeTry() | Error handling | [error, result] = await safeTry(fn) |
| measureTime() | Measure duration | {result, duration} |
| retryWithBackoff() | Retry with backoff | await retryWithBackoff(fn) |
| withTimeout() | Add timeout | await withTimeout(fn, 5000) |
| debouncePromise() | Debounced promise | debouncedFn() |
| throttlePromise() | Throttled promise | throttledFn() |
| batchProcess() | Batch processing | await batchProcess(items, batchSize) |
12. Object Utilities (@saffan/devtools-js/objects)
Object manipulation, deep cloning, and property access.
| Function | Description | Example |
|----------|-------------|---------|
| deepClone() | Deep clone | deepClone(obj) |
| pick() | Pick properties | pick(obj, ['a','b']) |
| omit() | Omit properties | omit(obj, ['password']) |
| merge() | Deep merge | merge(obj1, obj2) |
| isEmpty() | Check empty | isEmpty(obj) |
| deepEqual() | Deep equality | deepEqual(a, b) |
| memoize() | Memoize function | memoizedFn() |
| once() | Run once | onetimeFn() |
| limitCalls() | Limit calls | limitedFn() |
| get() | Get nested value | get(obj, 'a.b.c') |
| set() | Set nested value | set(obj, 'a.b.c', value) |
| has() | Has nested property | has(obj, 'a.b.c') |
| del() | Delete nested | del(obj, 'a.b.c') |
13. Core Utilities (Main Export)
These are the most commonly used utilities exported from the main package:
| Function | Description | Example |
|----------|-------------|---------|
| sleep() | Pause execution | await sleep(1000) |
| retry() | Retry with backoff | await retry(fn, {times:3}) |
| uuid() | Generate UUID | uuid() |
| logger | Colored logger | logger.info('msg') |
| readJSON() | Read JSON file | await readJSON('config.json') |
| writeJSON() | Write JSON file | await writeJSON('config.json', data) |
| fileExists() | Check file exists | await fileExists('file.txt') |
| timer() | Measure time | const end = timer('task'); end() |
| safeTry() | Safe async try | [err, data] = await safeTry(fn) |
| asyncQueue() | Concurrency limit | await asyncQueue(tasks, 3) |
| debounce() | Debounce function | debouncedFn() |
| throttle() | Throttle function | throttledFn() |
| hash() | Create hash | hash('data') |
| randomString() | Random string | randomString(16) |
| deepClone() | Deep clone | deepClone(obj) |
| isEmpty() | Check empty | isEmpty(val) |
| merge() | Deep merge | merge(obj1, obj2) |
| env | Env helpers | env.string('API_KEY') |
| formatError() | Format error | formatError(err) |
🖥️ CLI Tool
Use utilities directly from the command line:
# Generate UUID
npx @saffan/devtools-js uuid
# Hash text
npx @saffan/devtools-js hash "hello world"
# Generate random string
npx @saffan/devtools-js random 16
# Format bytes
npx @saffan/devtools-js bytes 1048576
# Check file exists
npx @saffan/devtools-js exists package.json
# Sleep/pause
npx @saffan/devtools-js sleep 1000
# Show library info
npx @saffan/devtools-js info📊 Feature Summary
| Category | Functions | Status | |----------|-----------|--------| | Array Utilities | 35+ | ✅ Complete | | Math Utilities | 60+ | ✅ Complete | Date Utilities | 80+ | ✅ Complete | | URL Utilities | 50+ | ✅ Complete | | CLI Utilities | 50+ | ✅ Complete | | System Utilities | 30+ | ✅ Complete | | File System Utilities | 50+ | ✅ Complete | | Data Structures | 15+ | ✅ Complete | | Stream Utilities | 30+ | ✅ Complete | | Crypto Utilities | 40+ | ✅ Complete | | Async Utilities | 10+ | ✅ Complete | | Object Utilities | 15+ | ✅ Complete | | Total | 500+ | ✅ Complete |
🎯 Why @saffan/devtools-js?
- Comprehensive - 500+ utilities covering all common development needs
- Zero dependencies - Only uses Node.js built-ins
- TypeScript ready - Full type definitions and JSDoc comments
- Production tested - Used in real applications with proper error handling
- Well documented - Comprehensive README with examples for every function
- CLI included - Use utilities from command line
- Modular - Import only what you need
- Maintainable - Follows best practices and coding standards
🧪 Real-world Examples
API Client with Retry
import { retry, logger } from '@saffan/devtools-js';
async function fetchWithRetry(url) {
return await retry(async () => {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}, {
times: 3,
delay: 200,
backoff: "exponential"
});
}Configuration Management
import { merge, env } from '@saffan/devtools-js';
const baseConfig = { port: 3000, debug: false };
const envConfig = {
port: env.number('PORT', 3000),
debug: env.bool('DEBUG', false)
};
const finalConfig = merge(baseConfig, envConfig);File Processing Pipeline
import { asyncQueue, readJSON, writeJSON } from '@saffan/devtools-js';
async function processFiles(files) {
const results = await asyncQueue(
files.map(file => async () => {
const data = await readJSON(file);
return transform(data);
}),
5 // 5 concurrent workers
);
await writeJSON('output.json', results);
}Date Range Calculations
import {
addDays, subDays,
startOfMonth, endOfMonth,
isBetween, format
} from '@saffan/devtools-js';
const today = new Date();
const monthStart = startOfMonth(today);
const monthEnd = endOfMonth(today);
const nextWeek = addDays(today, 7);
console.log(format(monthStart, 'YYYY-MM-DD'));
console.log(isBetween(today, monthStart, monthEnd));URL Manipulation
import {
parse, addQueryParam,
withProtocol, buildUrl
} from '@saffan/devtools-js';
const url = 'https://api.example.com/users';
const withParams = addQueryParam(url, 'page', 2);
const https = withProtocol(url, 'https');
const api = buildUrl('https', 'api.example.com', '/v1/users');🔧 TypeScript Support
All utilities include full TypeScript type definitions:
import { retry, asyncQueue, LRUCache } from '@saffan/devtools-js';
// Type-safe retry
await retry<User[]>(async () => {
return fetchUsers();
}, { times: 3 });
// Generic data structures
const cache = new LRUCache<string, User>(100);
cache.set('user1', { name: 'John' });
const user = cache.get('user1');🌐 Browser Support
The following utilities work in browser environments:
- Array Utilities - All functions
- Math Utilities - All functions
- Date Utilities - All functions (uses native Date)
- URL Utilities - All functions (uses native URL)
- Crypto - Uses Web Crypto API when available
The following require Node.js:
- CLI Utilities - Requires Node.js process/stderr
- System Utilities - Requires Node.js os/process
- File System Utilities - Requires Node.js fs module
- Stream Utilities - Requires Node.js streams
⚡ Performance
All utilities are optimized for performance:
- Zero runtime dependencies
- Minimal memory allocation
- Efficient algorithms (O(n) where possible)
- Tree-shakable ES modules
- No polyfills required
📁 Project Structure
devtools-js/
├── src/
│ ├── index.ts # Main exports
│ └── utils/
│ ├── array.ts # Array utilities
│ ├── math.ts # Math utilities
│ ├── date.ts # Date utilities
│ ├── url.ts # URL utilities
│ ├── cli.ts # CLI utilities
│ ├── system.ts # System utilities
│ ├── fs.ts # File system utilities
│ ├── structures.ts # Data structures
│ ├── stream.ts # Stream utilities
│ ├── crypto.ts # Crypto utilities
│ ├── async.ts # Async utilities
│ ├── objects.ts # Object utilities
│ └── strings.ts # String utilities
├── cli.js # CLI entry point
├── package.json # Package config
└── README.md # Documentation🤝 Contributing
Contributions welcome! This is an open-source project and we appreciate your help!
# Clone the repository
git clone https://github.com/SmartGenzAI1/devtools-js.git
cd devtools-js
# Install dependencies
npm install
# Build the project
npm run build
# Run tests
npm test
# Run in development mode
npm run devWays to Contribute:
- 🐛 Bug Reports - Open issues for bugs you find
- 🚀 Feature Requests - Suggest new utilities
- 📝 Documentation - Improve docs and examples
- 💻 Code Contributions - Add new features or fix bugs
- 🌟 Star the Repo - Show your support
- 📢 Spread the Word - Share on social media
📄 License
MIT License - see LICENSE file for details.
📞 Support
- GitHub Issues - Report bugs and request features
- GitHub Discussions - Ask questions and share ideas
- NPM - Package info and downloads
🙏 Acknowledgments
Thanks to all contributors who have helped make this project better!
Made with ❤️ by SmartGenzAI1
⭐ Star us on GitHub if you find this useful!
