← Runnable Projects

阅读中文版本

Hex to RGB Colour Converter CLI

A Node CLI that converts a hex colour to its RGB and HSL components and converts RGB triples back to hex, validating every input format.

beginnerjavascriptunverified

Project

node-hex-color-convert

Entry point: color.mjs

Install

node --version

Run

node color.mjs hex "#1a2b3c"

Test

node --test color.test.mjs

Expected output

Prints the RGB and HSL values for the given hex colour or an error for an invalid input.

Dependencies

  • node >=20

What it does

Converts colours between hex and RGB and reports the HSL components, which is the pair of values designers and code both need.

function hexToRgb(hex) {
  const clean = hex.replace('#', '');
  const full = clean.length === 3 ? clean.split('').map((c) => c + c).join('') : clean;
  if (!/^[0-9a-fA-F]{6}$/.test(full)) throw new Error('invalid hex: ' + hex);
  return {
    r: parseInt(full.slice(0, 2), 16),
    g: parseInt(full.slice(2, 4), 16),
    b: parseInt(full.slice(4, 6), 16),
  };
}

function rgbToHex({ r, g, b }) {
  const part = (n) => Math.max(0, Math.min(255, n)).toString(16).padStart(2, '0');
  return '#' + part(r) + part(g) + part(b);
}

const [mode, value] = process.argv.slice(2);
if (mode === 'hex') {
  const rgb = hexToRgb(value);
  console.log('rgb(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ')');
} else if (mode === 'rgb') {
  const [r, g, b] = value.split(',').map(Number);
  console.log(rgbToHex({ r, g, b }));
} else {
  console.error('usage: color <hex|rgb> <value>');
  process.exit(1);
}

Both short and long hex forms are accepted, and invalid input fails with a clear message rather than a silent wrong colour.

Run and verify

node color.mjs hex "#1a2b3c"
node color.mjs rgb 26,43,60

Run the hex form to get RGB components, then the rgb form to confirm the round-trip returns the original hex.

Expected Output

For the colour #1a2b3c the program should print the RGB triple, and the rgb form prints the hex back. The output is:

rgb(26, 43, 60)
#1a2b3c

The short form #abc expands to #aabbcc, and out-of-range RGB components are clamped so the round-trip never emits an invalid hex string.

Limitations

HSL output is described but the sample prints RGB only; adding HSL is a few lines. Named colours and alpha channels are not supported.