UUID v4 Generator CLI
A minimal CLI that prints cryptographically random RFC 4122 version 4 UUIDs using the built-in crypto module, one per line, with format validation.
Project
node-uuid-v4-cli
Entry point: uuid.mjs
Install
node --versionRun
node uuid.mjs 3Test
node --test uuid.test.mjsExpected output
Running with the argument 3 prints three lines, each a 36-character UUID with version 4 and variant bits set.Dependencies
- node >=20
What it does
Prints cryptographically random RFC 4122 version 4 UUIDs using the built-in crypto.randomUUID. The count argument is clamped to between 1 and 1000.
import { randomUUID } from 'node:crypto';
export function generate(count) {
const n = Math.max(1, Math.min(1000, count));
return Array.from({ length: n }, () => randomUUID());
}
export function isV4(uuid) {
return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(uuid);
}
const arg = Number(process.argv[2] ?? 1);
for (const uuid of generate(Number.isFinite(arg) ? arg : 1)) {
console.log(uuid);
}
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { generate, isV4 } from './uuid.mjs';
test('generated uuids match the v4 shape and are unique', () => {
const ids = generate(200);
assert.equal(ids.length, 200);
for (const id of ids) assert.ok(isV4(id), 'bad uuid ' + id);
assert.equal(new Set(ids).size, 200);
});
test('count is clamped to a sane range', () => {
assert.equal(generate(0).length, 1);
assert.equal(generate(5000).length, 1000);
});
Run and verify
node --test uuid.test.mjs
node uuid.mjs 3
Run the tests to confirm shape and uniqueness, then generate three UUIDs on the command line.
Expected Output
The test run should print two passing tests for the v4 shape and the count clamp. The demo’s console.log output should print one UUID per line — the values themselves are random, but each should match the 8-4-4-4-12 lowercase hex layout with version and variant bits in place:
3b241101-e2bb-4f5e-8d7c-1a2b3c4d5e6f
8f14e45f-ceea-467f-a830-a1b2c3d4e5f0
5d6e7f80-1234-4abc-9def-0123456789ab
Every line’s third group starts with 4 (version 4) and the fourth group starts with 8, 9, a, or b (variant 10x) — the regex in isV4 encodes exactly those positions, and generating three means three distinct values since the entropy source is crypto.randomUUID.
Limitations
Only version 4 UUIDs are produced; sortable or namespace-based v1/v3/v5 variants are out of scope.