← Runnable Projects

阅读中文版本

Random Password Generator CLI

A Node CLI that generates a cryptographically random password of a chosen length using a rejection-sampled character set to avoid modulo bias.

beginnerjavascriptunverified

Project

node-random-password-cli

Entry point: genpass.mjs

Install

node --version

Run

node genpass.mjs 20

Test

node --test genpass.test.mjs

Expected output

Prints a random password of the requested length drawn from letters, digits, and symbols, using crypto randomness.

Dependencies

  • node >=20

What it does

Draws characters with crypto.randomInt, which rejection-samples rather than taking a modulo, so every character is uniformly likely. Length is validated before generation.

import { randomInt } from 'node:crypto';

const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789!#$%&*+-=?@^_';

export function generate(length = 16) {
  if (!Number.isInteger(length) || length < 8 || length > 128) throw new RangeError('length must be 8..128');
  let out = '';
  for (let i = 0; i < length; i++) out += ALPHABET[randomInt(ALPHABET.length)];
  return out;
}

console.log(generate(Number(process.argv[2] ?? 16)));

Run and verify

node genpass.mjs 20

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

Expected Output

For length 20 the tool prints a 20-character password; the exact value changes every run:

G7#pLq2$vXr9!mTz4wKc

Limitations

Uses a fixed alphabet that excludes visually ambiguous characters; it does not enforce per-class minimums, so occasionally a password may contain only one character class.