← Runnable Projects

阅读中文版本

UUID Validate and Inspect CLI

A Node CLI that validates a UUID string, reports its version and variant bits, and normalizes it to canonical lowercase form.

beginnerjavascriptunverified

Project

node-uuid-validate

Entry point: uuid.mjs

Install

node --version

Run

node uuid.mjs 550e8400-e29b-41d4-a716-446655440000

Test

node --test uuid.test.mjs

Expected output

Prints whether the input is a valid UUID and, if so, its version and variant plus the normalized value.

Dependencies

  • node >=20

What it does

Checks the string against the 8-4-4-4-12 hex layout, reads the version nibble and variant bits, lowercases the result, and reports validity with a reason when the format is wrong.

const RE = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i;

export function inspect(input) {
  const m = String(input).trim().match(RE);
  if (!m) return { valid: false };
  const normalized = m[0].toLowerCase();
  const version = parseInt(normalized[14], 16);
  const variantNibble = parseInt(normalized[19], 16);
  const variant = variantNibble >= 8 && variantNibble <= 11 ? 'RFC 4122' : 'other';
  return { valid: true, version, variant, normalized };
}

const { valid, version, variant, normalized } = inspect(process.argv[2] ?? '');
console.log(valid
  ? 'valid v' + version + ' variant ' + variant + ' -> ' + normalized
  : 'invalid uuid');

Run and verify

node uuid.mjs 550e8400-e29b-41d4-a716-446655440000

Run the test command to check the implementation: node --test uuid.test.mjs.

Expected Output

The canonical v4 example is valid; the tool prints a one-line report:

valid v4 variant RFC 4122 -> 550e8400-e29b-41d4-a716-446655440000

Limitations

Format validation only: it cannot tell whether a well-formed UUID was actually generated randomly or is a nil, max, or v1 value reused from another source.