Try it yourself with our free Color Picker tool — runs entirely in your browser, no signup needed.

How to Convert colors (HEX/RGB/HSL) in Node.js

How to Convert Colors (HEX/RGB/HSL) in Node.js

Converting colors between different formats is a common task in web development, particularly when working with design files, APIs, or user input. In Node.js, converting colors can be achieved using a combination of string manipulation and mathematical calculations. In this guide, we will explore how to convert colors between HEX, RGB, and HSL formats in Node.js.

Quick Example

Here is a minimal example that converts a HEX color to RGB:

const hexToRgb = (hex) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
};

console.log(hexToRgb('#ffffff')); // Output: { r: 255, g: 255, b: 255 }

This code uses a regular expression to extract the RGB values from a HEX string and then converts them to integers using parseInt.

Step-by-Step Breakdown

Let's break down the code line by line:

  • const hexToRgb = (hex) => { ... }: We define a function hexToRgb that takes a HEX string as input.
  • const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);: We use a regular expression to match the HEX string. The regular expression ^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$ breaks down as follows:
    • ^: Matches the start of the string.
    • #?: Matches an optional # character.
    • ([a-f\d]{2}): Matches exactly 2 hexadecimal digits (0-9, a-f) and captures them as a group.
    • $: Matches the end of the string.
    • i: Makes the regular expression case-insensitive.
  • return result ? { ... } : null;: If the regular expression matches, we return an object with the extracted RGB values. If not, we return null.

Handling Edge Cases

Here are some common edge cases to consider:

Empty/Null Input

console.log(hexToRgb('')); // Output: null
console.log(hexToRgb(null)); // Output: null

In this case, we return null to indicate that the input is invalid.

Invalid Input

console.log(hexToRgb(' invalid hex ')); // Output: null

Again, we return null to indicate that the input is invalid.

Large Input

console.log(hexToRgb('#ffffffffffffffff')); // Output: null

In this case, the regular expression will not match, and we return null.

Unicode/Special Characters

console.log(hexToRgb('#ffffff\u200b')); // Output: null

The regular expression will not match, and we return null.

Common Mistakes

Here are some common mistakes to avoid:

Mistake 1: Not Handling Null Input

const hexToRgb = (hex) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  };
};

console.log(hexToRgb(null)); // Error: Cannot read property '1' of null

Corrected Code

const hexToRgb = (hex) => {
  if (!hex) return null;
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
};

Mistake 2: Not Handling Invalid Input

const hexToRgb = (hex) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  };
};

console.log(hexToRgb(' invalid hex ')); // Error: Cannot read property '1' of null

Corrected Code

const hexToRgb = (hex) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
};

Mistake 3: Not Handling Large Input

const hexToRgb = (hex) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  };
};

console.log(hexToRgb('#ffffffffffffffff')); // Error: Cannot read property '1' of null

Corrected Code

const hexToRgb = (hex) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
};

Performance Tips

Here are some practical performance tips:

  • Use a cached regular expression to improve performance when converting multiple colors.
  • Use a library like color-convert to convert colors, which is optimized for performance.
  • Avoid converting colors unnecessarily, and instead store the converted values in a cache.

FAQ

Q: How do I convert RGB to HEX?

A: You can use the following function:

const rgbToHex = (rgb) => {
  const { r, g, b } = rgb;
  return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
};

Q: How do I convert HSL to RGB?

A: You can use the following function:

const hslToRgb = (hsl) => {
  const { h, s, l } = hsl;
  const r = l + s * Math.cos(h * 2 * Math.PI);
  const g = l + s * Math.cos((h + 1/3) * 2 * Math.PI);
  const b = l + s * Math.cos((h + 2/3) * 2 * Math.PI);
  return { r, g, b };
};

Q: Can I use this code in a browser?

A: Yes, this code is compatible with modern browsers.

Q: How do I handle alpha transparency?

A: You can add an alpha channel to the RGB object and use the rgba function to convert it to HEX.

Q: Can I use this code in a Node.js module?

A: Yes, this code is compatible with Node.js and can be used in a module.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp