Skip to content

itw-creative-works/node-powertools

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

90 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation




Site | NPM Module | GitHub Repo

Node Powertools is a lightweight utility library for Node.js and the browser — randomness, type coercion, async control flow, string manipulation, object validation, and more.

Install

npm

npm install node-powertools
// ESM
import Powertools from 'node-powertools';

// CJS
const Powertools = require('node-powertools');

CDN

<script src="https://cdn.jsdelivr.net/npm/node-powertools@latest/dist/powertools.min.js"></script>
<script>
  // The script above exposes the global variable 'Powertools'
  Powertools.random(0, 100);
</script>

Randomness

Powertools.random(min, max, options)

Generate a random number between min and max. If an array is supplied as the first argument, a random element is returned.

Options:

  • mode: 'uniform' (default) or 'gaussian' — distribution mode
  • skew: 0.5 (default) — gaussian only; controls where the peak sits (0 = min, 0.5 = middle, 1 = max)
Powertools.random(0, 100); // 69
Powertools.random(0, 100, {mode: 'gaussian'}); // 52 (more likely near 50)
Powertools.random(0, 100, {mode: 'gaussian', skew: 0.8}); // 73 (peak shifted toward 80)
Powertools.random(['Apple', 'Orange', 'Pear']); // Orange

Powertools.chance(probability)

Returns true or false based on the given probability (0 to 1).

Powertools.chance(0.5); // 50% chance of true
Powertools.chance(0.9); // 90% chance of true
Powertools.chance(0); // Always false
Powertools.chance(1); // Always true

Arrays

Powertools.arrayify(input)

Wrap a value in an array if it isn't one already.

Powertools.arrayify(1); // [1]
Powertools.arrayify([1]); // [1]

Powertools.uniquify(arr)

Remove duplicate elements from an array. Works with primitives and objects.

Powertools.uniquify([1, 2, 2, 3]); // [1, 2, 3]
Powertools.uniquify([{id: 1}, {id: 1}, {id: 2}]); // [{id: 1}, {id: 2}]

Async

Powertools.wait(min, max)

Wait for a specified time in milliseconds. If max is provided, waits a random duration between min and max.

await Powertools.wait(1000); // Wait exactly 1 second
await Powertools.wait(1000, 3000); // Wait random time between 1-3 seconds

Powertools.poll(fn, options)

Poll a function until it returns true. Supports sync and async functions. Rejects on timeout.

Options:

  • interval: 100 (default) — polling interval in ms
  • timeout: 2000 (default) — max wait time; set to 0 for infinite
await Powertools.poll(() => something === true, {interval: 100, timeout: 30000});

await Powertools.poll(async (index) => {
  const result = await checkSomething();
  return result.isReady;
}, {interval: 500, timeout: 10000});

Powertools.queue(options)

Create a task queue that processes async functions in FIFO order with optional concurrency control.

Options:

  • concurrency: 1 (default) — number of tasks to run simultaneously
  • delay: 0 (default) — delay in ms between executions
// Serial queue (default)
const queue = Powertools.queue();
queue.add(async () => 'first');
queue.add(async () => 'second'); // Runs after first completes

// Concurrent queue — process up to 20 tasks at a time
const pool = Powertools.queue({concurrency: 20});
const results = await Promise.all(
  urls.map((url) => pool.add(() => fetch(url))),
);

Powertools.iterate(arr, callback)

Process each element sequentially with an async callback. Each iteration waits for the previous one to complete.

await Powertools.iterate([1, 2, 3], async (item, index) => {
  console.log(`Processing ${item} at index ${index}`);
  await Powertools.wait(1000);
});

Powertools.getPromiseState(promise)

Synchronously check the state of a promise: 'pending', 'resolved', or 'rejected'. Node.js only.

const promise = new Promise((resolve) => setTimeout(resolve, 1000));
Powertools.getPromiseState(promise); // 'pending'

Powertools.waitForPendingPromises(promises, options)

Poll an array of promises and wait until the number of pending promises drops below max. Node.js only.

Options:

  • max: 10 (default) — maximum number of pending promises allowed
  • timeout: 60000 (default) — max wait time in ms
const promises = [Powertools.wait(1000), Powertools.wait(2000), Powertools.wait(3000)];
await Powertools.waitForPendingPromises(promises, {max: 2, timeout: 5000});

Strings

Powertools.template(str, data, options)

Replace {key} placeholders in a string with values from data. Supports nested keys with dot notation.

Options:

  • escape: true in browser, false in Node (default) — escape HTML characters
  • brackets: ['{', '}'] (default) — custom bracket characters
Powertools.template('Hello {name}', {name: 'World'}); // 'Hello World'
Powertools.template('{user.name}', {user: {name: 'Jon'}}); // 'Jon'
Powertools.template('{{x}}', {x: 1}, {brackets: ['{{', '}}']}); // '1'

Powertools.hyphenate(str, options)

Convert a string to kebab-case.

Options:

  • removeNonAlphanumeric: true (default) — strip non-alphanumeric characters
  • lowercase: true (default) — convert to lowercase
Powertools.hyphenate('Hello World'); // 'hello-world'
Powertools.hyphenate('Hello World', {lowercase: false}); // 'Hello-World'

Powertools.escape(str)

Escape special characters in a string for use in a RegExp.

Powertools.escape('.*+?'); // '\\.\\*\\+\\?'

Powertools.regexify(str)

Convert a string into a RegExp. Supports flags.

Powertools.regexify('/Apple/i'); // RegExp /Apple/i

Objects

Powertools.defaults(settings, schema)

Validate and structure a settings object against a schema. Fills in missing keys, enforces types, applies min/max constraints, and strips unknown keys.

Schema Properties:

  • types: Array of valid types ('string', 'number', 'boolean', 'array', 'function', 'any')
  • default: Value to use if the key is missing (can be a function)
  • value: Force this value regardless of input (can be a function)
  • min: Minimum value (for numbers) or minimum length (for strings/arrays)
  • max: Maximum value (for numbers) or maximum length (for strings/arrays)
const schema = {
  name: { types: ['string'], default: '', max: 10 },
  stats: {
    level: { types: ['number'], default: 1, min: 1, max: 10 },
    admin: { value: false },
  },
};

Powertools.defaults({}, schema);
// {name: '', stats: {level: 1, admin: false}}

Powertools.defaults({name: 'A very long name', stats: {level: 50}}, schema);
// {name: 'A very lon', stats: {level: 10, admin: false}}

Powertools.whitelist(obj, keys)

Return a new object with only the specified keys. Supports nested keys with dot notation.

Powertools.whitelist({a: 1, b: 2, c: 3}, ['a', 'c']); // {a: 1, c: 3}
Powertools.whitelist({user: {name: 'Jon', age: 25}}, ['user.name']); // {user: {name: 'Jon'}}

Powertools.getKeys(obj)

Recursively return all keys in an object using dot notation.

Powertools.getKeys({name: 'Jon', favorites: {color: 'red'}}); // ['name', 'favorites.color']

Powertools.isObject(obj)

Check if a value is a plain object. Returns false for null, arrays, and other non-object types.

Powertools.isObject({}); // true
Powertools.isObject(null); // false
Powertools.isObject([]); // false

Powertools.stringify(obj, replacer, spaces, cycleReplacer)

Safely stringify an object to JSON, handling circular references.

const obj = {name: 'Jon'};
obj.self = obj;
Powertools.stringify(obj); // '{"name":"Jon","self":"[Circular ~]"}'

Type Coercion

Powertools.force(value, type, options)

Intelligently convert a value to a target type. Supported types: string, number, boolean, array, undefined.

Array Options:

  • trim: true (default) — trim whitespace from string elements
  • force: 'string', 'number', or 'boolean' — coerce each element to a specific type
Powertools.force('true', 'boolean'); // true
Powertools.force('1,2,3', 'array'); // ['1', '2', '3']
Powertools.force('1,2,3', 'array', {force: 'number'}); // [1, 2, 3]
Powertools.force(undefined, 'string'); // ''

Utilities

Powertools.timestamp(date, options)

Convert a date into an ISO string, UNIX timestamp, or Date object.

Options:

  • output: 'string' (default), 'unix', or 'date'
Powertools.timestamp(new Date('2999/12/31'), {output: 'string'}); // '2999-12-31T08:00:00.000Z'
Powertools.timestamp(new Date('2999/12/31'), {output: 'unix'}); // 32503622400
Powertools.timestamp(); // Current timestamp as ISO string

Powertools.parseProxy(proxy)

Parse a proxy string into a structured object. Supports HTTP, SOCKS4, and SOCKS5 protocols.

const proxy = Powertools.parseProxy('http://user:pass@1.2.3.4:8080');
proxy.host; // '1.2.3.4'
proxy.port; // '8080'
proxy.valid; // true
proxy.toString(); // 'http://user:pass@1.2.3.4:8080'
proxy.toString({auth: false}); // 'http://1.2.3.4:8080'

Powertools.execute(command, options, setupCallback)

Execute a shell command using child_process.spawn(). Node.js only.

Options:

  • log: false (default) — stream output to stdout/stderr in real-time
  • debug: false (default) — log debug information
  • config: {} (default) — options passed to spawn() (cwd, shell, stdio, etc.)
const output = await Powertools.execute('ls -a');
await Powertools.execute('npm install', {log: true});
await Powertools.execute('long-command', {}, (child) => {
  child.on('exit', (code) => console.log('Exited with', code));
});

Packages

 
 
 

Contributors