Duration Format CLI
A Node CLI that converts a duration in milliseconds to a compact human string such as 1h 2m 3s, and parses that format back to milliseconds.
Project
node-duration-format-cli
Entry point: duration.mjs
Install
node --versionRun
node duration.mjs format 3723000Test
node --test duration.test.mjsExpected output
Prints the human-readable duration, for example 1h 2m 3s for 3723000 milliseconds, and parse returns milliseconds.Dependencies
- node >=20
What it does
Decomposes a millisecond count into days, hours, minutes, seconds, and milliseconds, then prints the non-zero units in descending order. Parsing reverses the process by summing each unit token.
const UNITS = [['d', 86400000], ['h', 3600000], ['m', 60000], ['s', 1000], ['ms', 1]];
export function format(ms) {
if (!Number.isFinite(ms) || ms < 0) throw new RangeError('duration must be a non-negative number');
let rest = Math.floor(ms);
const parts = [];
for (const [label, size] of UNITS) {
const n = Math.floor(rest / size);
if (n > 0) parts.push(n + label);
rest -= n * size;
}
return parts.length ? parts.join(' ') : '0ms';
}
export function parse(text) {
const re = /(\d+)\s*(d|h|m|s|ms)/g;
let total = 0; let m;
while ((m = re.exec(text))) total += Number(m[1]) * (UNITS.find(([u]) => u === m[2])[1]);
return total;
}
const [mode, arg] = process.argv.slice(2);
console.log(mode === 'parse' ? parse(arg) : format(Number(arg)));
Run and verify
node duration.mjs format 3723000
Run the test command to check the implementation: node --test duration.test.mjs.
Expected Output
3723000 ms is one hour, two minutes, and three seconds:
1h 2m 3s
Limitations
Supports durations up to days only; months and years are excluded because their length varies and would make the parse ambiguous.