color-logging
Version:
Une librairie simple et optimisée qui te permet de styliser tes console.log.
34 lines (26 loc) • 1.31 kB
JavaScript
function toRGB(hex) {
hex = hex.replace("#", "");
if (hex.length === 3) hex = hex.split("").map(c => c + c).join("");
const num = parseInt(hex, 16);
return { red: (num >> 16) & 255, green: (num >> 8) & 255, blue: num & 255 };
}
function validHEX(hex) {
return typeof hex === "string" && /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(hex);
}
String.prototype.color = function ({ text = "#FFFFFF", back = null, date = false } = {}) {
if (!validHEX(text) || (back !== null && !validHEX(back) || typeof date !== "boolean")) return this.toString();
const { red: textRed, green: textGreen, blue: textBlue } = toRGB(text);
let colorCode = `\x1b[38;2;${textRed};${textGreen};${textBlue}m`;
if (back) {
const { red: backRed, green: backGreen, blue: backBlue } = toRGB(back);
colorCode += `\x1b[48;2;${backRed};${backGreen};${backBlue}m`;
}
const content = this.toString();
let response = "";
if (date) {
response += `[${new Date().toLocaleString("fr-FR", { timeZone: "Europe/Paris", hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit", day: "2-digit", month: "2-digit", year: "numeric" })}] `;
}
response += colorCode + content + "\x1b[0m";
return response;
};
module.exports = {};