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.
npm install node-powertools// ESM
import Powertools from 'node-powertools';
// CJS
const Powertools = require('node-powertools');<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>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 modeskew: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']); // OrangeReturns 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 trueWrap a value in an array if it isn't one already.
Powertools.arrayify(1); // [1]
Powertools.arrayify([1]); // [1]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}]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 secondsPoll a function until it returns true. Supports sync and async functions. Rejects on timeout.
Options:
interval:100(default) — polling interval in mstimeout:2000(default) — max wait time; set to0for 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});Create a task queue that processes async functions in FIFO order with optional concurrency control.
Options:
concurrency:1(default) — number of tasks to run simultaneouslydelay: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))),
);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);
});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'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 allowedtimeout: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});Replace {key} placeholders in a string with values from data. Supports nested keys with dot notation.
Options:
escape:truein browser,falsein Node (default) — escape HTML charactersbrackets:['{', '}'](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'Convert a string to kebab-case.
Options:
removeNonAlphanumeric:true(default) — strip non-alphanumeric characterslowercase:true(default) — convert to lowercase
Powertools.hyphenate('Hello World'); // 'hello-world'
Powertools.hyphenate('Hello World', {lowercase: false}); // 'Hello-World'Escape special characters in a string for use in a RegExp.
Powertools.escape('.*+?'); // '\\.\\*\\+\\?'Convert a string into a RegExp. Supports flags.
Powertools.regexify('/Apple/i'); // RegExp /Apple/iValidate 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}}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'}}Recursively return all keys in an object using dot notation.
Powertools.getKeys({name: 'Jon', favorites: {color: 'red'}}); // ['name', 'favorites.color']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([]); // falseSafely stringify an object to JSON, handling circular references.
const obj = {name: 'Jon'};
obj.self = obj;
Powertools.stringify(obj); // '{"name":"Jon","self":"[Circular ~]"}'Intelligently convert a value to a target type. Supported types: string, number, boolean, array, undefined.
Array Options:
trim:true(default) — trim whitespace from string elementsforce:'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'); // ''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 stringParse 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'Execute a shell command using child_process.spawn(). Node.js only.
Options:
log:false(default) — stream output to stdout/stderr in real-timedebug:false(default) — log debug informationconfig:{}(default) — options passed tospawn()(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));
});