node_shims
node_shims copied to clipboard
Deno color logging support in nodejs
Reference: https://examples.deno.land/color-logging
After months of thinking, I came up with this code that achieves color logging:
let chalk = await Import("[email protected]");
let oc = console;
function styled(type, message, ...styles) {
// Split the message by the placeholder %c and trim the spaces
let messageArray = message.split("%c").map((e) => e.trim());
// Remove the first empty string
if (messageArray[0].trim() == "") messageArray.shift();
// Initialize an array to store the chalk objects
let chalkArray = [];
// Loop through the styles array and create the chalk objects
for (let style of styles) {
// Split the style string by semicolons and trim the spaces
let styleArray = style.split(";").map((s) => s.trim());
// Initialize a chalk object
let chalkObject = chalk;
// Loop through the style array and apply the corresponding methods to the chalk object
for (let s of styleArray) {
// Split the style by colon and trim the spaces
let [property, value] = s.split(":").map((s) => s.trim());
// Convert the property and value to lower case
property = property.toLowerCase();
value = value.toLowerCase();
// Switch on the property and apply the value as a method to the chalk object
switch (property) {
case "color":
chalkObject = chalkObject[value];
break;
case "font-weight":
if (value === "bold") {
chalkObject = chalkObject.bold;
}
break;
case "font-style":
if (value === "italic") {
chalkObject = chalkObject.italic;
}
break;
case "text-decoration":
if (value === "underline") {
chalkObject = chalkObject.underline;
}
break;
default:
// Ignore other properties
break;
}
}
// Push the chalk object to the chalk array
chalkArray.push(chalkObject);
}
// Initialize a string to store the final message
let finalMessage = "";
// Loop through the message array and the chalk array and concatenate the styled messages
for (let i = 0; i < messageArray.length; i++) {
// If there is a chalk object for the current index, apply it to the message
if (chalkArray[i]) {
finalMessage += " " + chalkArray[i](messageArray[i]);
} else {
// Otherwise, just append the message
finalMessage += " " + messageArray[i];
}
}
// Log the final message
oc[type](finalMessage.trim());
}
//Polyfill global console object with below:
globalThis.console={
log: (...args)=>styled("log", ...args)
// Add other functions here like warn, error, info
}
//use it normally
console.log("%cHello %cWorld", "color: red", "color: blue");
The Import
function is my custom function, dont worry about it and we need a chalk alternative maybe or we can just use it?
This is how it looks: