@ideadesignmedia/helpers
v1.0.18
Published
A small but opinionated Node.js utility belt from Idea Design Media. It covers stream helpers, compression, filesystem shortcuts, HTTP helpers, collection utilities, numeric helpers, and quick validators. The library is written in CommonJS but ships with
Readme
@ideadesignmedia/helpers
A small but opinionated Node.js utility belt from Idea Design Media. It covers stream helpers, compression, filesystem shortcuts, HTTP helpers, collection utilities, numeric helpers, and quick validators. The library is written in CommonJS but ships with full TypeScript declarations.
Installation
npm install @ideadesignmedia/helpers
# or
yarn add @ideadesignmedia/helpersUsage
CommonJS
const helpers = require("@ideadesignmedia/helpers");
const { gzip, readFile, filter } = helpers;ES Modules / TypeScript
import helpers, { gzip, type Helpers } from "@ideadesignmedia/helpers";
await gzip("./logs/today.txt", "./logs/today.txt.gz");Note: To use the default import from TypeScript enable
esModuleInterop(orallowSyntheticDefaultImports) in yourtsconfig. Otherwise useimport helpers = require("@ideadesignmedia/helpers").
TypeScript Support
The package now includes a hand-written index.d.ts file that mirrors the runtime API. Highlights:
- Strongly typed
FilterDescriptor,SortDescriptor, andFilterModeinterfaces for the dynamic filtering helpers. - Overloads for functions such as
writeFile,compare, andtimeoutto reflect their different behaviours. - Full typings for Node.js primitives like
BufferingTransform,RequestOptions, and HTTP headers. - Namespace-style types (
Helpers.FilterDescriptor,Helpers.SortDescriptor, etc.) that stay in sync with the runtime exports.
API Reference
Streams & Compression
BufferingTransform(options?)- Transform stream that buffers up tocapacitychunks before releasing them. Handy when a downstream consumer needs async setup time. Accepts all NodeTransformOptionspluscapacity(default3).const { pipeline } = require("stream"); const { BufferingTransform } = require("@ideadesignmedia/helpers"); pipeline(source, new BufferingTransform({ capacity: 5 }), destination, console.error);gzip(file, dest)- Pipesfilethrough gzip compression and writes todest. Resolves with the destination path.unzipGzip(file, dest)- Inverse ofgzip, inflating a.gzfile intodest.unzip(input, output)- Usesextract-zipto unpack archives. Resolves with the absolute output directory.zip(input, outputPath, glob?)- Creates a zip archive usingarchiver. Provide either a directory path or a glob pattern. Optionalglobsettings are forwarded toarchiver.glob.
Filesystem & Serialization
readFile(file)- Async file read. Parses.jsonfiles before resolving, otherwise returns the rawBuffer.writeFile(path, data, readBack?)- Writes strings, buffers, or objects (auto JSON stringification). WhenreadBackistrue, resolves with the result ofreadFile; otherwise resolves totrue.copyDir(source, destination, callback)- Recursive directory copy that mirrors the folder structure before invoking the callback.jsonl(array)- Serialises an array of objects into JSON Lines (newline-delimited JSON) format.
Networking
download(link, destination, options?, timeout?)- Streams an HTTP(S) response to disk. Optional request options and timeout in milliseconds.upload(filepath, url, headers?, method?, options?)- Pushes a local file to an HTTP endpoint, settingContent-TypeandContent-Lengthautomatically. Resolves with parsed JSON.request(url, options?, body?)- Convenience wrapper aroundhttp.requestorhttps.request. Resolves with parsed JSON when possible or the raw response string otherwise.
Timing & Control Flow
timeout(callback, ms, args?)- Awaitable wrapper oversetTimeoutthat safely handles extremely large delays by chunking them. Resolves with either the callback result or the native timeout handle.compare(a, b)- Deep comparison helper. Supports dates, arrays, objects, and even functional comparators (compare(fn, value)runs the predicate).
Collections & Objects
filter(data, filters)- Multi-purpose filtering engine. Each filter descriptor looks like:
Supports string, number, array, object, and date comparisons, nested comparisons viaconst filters: Helpers.FilterDescriptor<User>[] = [ { name: "age", type: "number", mode: { name: "gte", value: 18 } }, { name: "tags", type: "array", mode: { name: "includes", value: "pro" } } ]; const adults = helpers.filter(users, filters);mode.compare("or","not", etc.), and optional match limits viacount.sort(data, fields)- Multi-level sorter. Each descriptor hasname, optionaltype, anddirection(truefor descending). Note: sorts happen in place.search(value, items, indexes)- Builds buckets of matching records keyed by the field that matched.swap(array, a, b)- Returns a shallow-copied array with two indices swapped.insert(array, from, to)- Moves one element from indexfromtoto. The original array is mutated because it relies onsplice-- clone first if you need immutability.index(array, page, size)- Simple pagination helper returning the slice for the requested page.compareArrays(next, prev)- Returns{ added, removed }diffs between two arrays.filterKeys(obj, keys)- Omits provided keys from an object, returning a shallow clone.
Numbers & Math
parseNumber(value)- SafeparseFloatwrapper that falls back to0.sum(values)- Adds numeric or numeric-string values together.average(values)- Arithmetic mean helper.movingAverage(values, days)- Simple moving average over the firstdaysentries.EMA(values, days)- Exponential moving average using the smoothing constant2 / (days + 1).standardDeviation(values)- Sample standard deviation (note: mutates the input array because it callssplice).round(value)- Bankers-style rounding that prefers the nearest integer when.5is involved.currency(num)- Locale-aware formatting with two decimal places.
Strings & Validation
isEmail(value),isAlphanumeric(value),isLetters(value)- Regex validators.isDate(value)- Checks that a string can be parsed into a valid date.nameCompare(a, b)- Case-insensitive comparator that returns-1,0, or1; ideal forArray.prototype.sort.
Security
encrypt(plain, key?, buffer?)anddecrypt(cipher, key?, buffer?)- AES-256-CTR helpers. Thebufferargument must be a 16-character initialization vector string.
Examples
A few quick patterns:
import helpers from "@ideadesignmedia/helpers";
// Filter and paginate a dataset
const filtered = helpers.filter(users, [
{ name: "status", type: "string", mode: { name: "equal", value: "active" } }
]);
const page = helpers.index(filtered, 0, 25);
// Stream upload a zipped directory
await helpers.zip("./dist", "./dist.zip");
await helpers.upload("./dist.zip", "https://api.example.com/upload", { Authorization: "Bearer token" });
// Serialize logs to JSONL and gzip them
const body = helpers.jsonl(logEntries);
await helpers.writeFile("./logs/run.jsonl", body);
await helpers.gzip("./logs/run.jsonl", "./logs/run.jsonl.gz");License
MIT (c) Idea Design Media
