Created
November 18, 2020 05:11
-
-
Save htdangkhoa/c27bf00c8accae653d568e4d53a065c1 to your computer and use it in GitHub Desktop.
Override node js console.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { readFileSync } from 'fs'; | |
import { resolve } from 'path'; | |
const pkg = JSON.parse( | |
readFileSync(resolve(process.cwd(), 'package.json'), 'utf-8').toString(), | |
); | |
const DATE_FORMAT = 'DD-MM-YYYY-hh:mm:ss.SSS'; | |
const colors = { | |
reset: '\x1b[0m', | |
fg: { | |
magenta: '\x1b[35m', | |
blue: '\x1b[34m', | |
red: '\x1b[31m', | |
green: '\x1b[32m', | |
cyan: '\x1b[36m', | |
warn: '\x1b[33m', | |
white: '\x1b[37m', | |
}, | |
bg: { | |
magenta: '\x1b[45m', | |
blue: '\x1b[44m', | |
red: '\x1b[41m', | |
green: '\x1b[42m', | |
cyan: '\x1b[46m', | |
warn: '\x1b[43m', | |
white: '\x1b[47m', | |
}, | |
}; | |
const mapping = { | |
assert: [colors.fg.magenta, colors.bg.magenta], | |
debug: [colors.fg.blue, colors.bg.blue], | |
error: [colors.fg.red, colors.bg.red], | |
info: [colors.fg.green, colors.bg.green], | |
trace: [colors.fg.cyan, colors.bg.cyan], | |
warn: [colors.fg.warn, colors.bg.warn], | |
}; | |
['assert', 'debug', 'error', 'info', 'trace', 'warn', 'log'].forEach((name) => { | |
const method = name === 'log' ? 'info' : name; | |
const oldMethod = console[name].bind(console); | |
console[name] = (...args) => { | |
const date = new Date(); | |
const getDate = () => | |
DATE_FORMAT.replace('DD', date.getDate().toString().padStart(2, '0')) | |
.replace('MM', (date.getMonth() + 1).toString().padStart(2, '0')) | |
.replace('YYYY', date.getFullYear().toString().padStart(4, '0')) | |
.replace('hh', date.getHours().toString().padStart(2, '0')) | |
.replace('mm', date.getMinutes().toString().padStart(2, '0')) | |
.replace('ss', date.getSeconds().toString().padStart(2, '0')) | |
.replace('SSS', date.getMilliseconds().toString().padStart(3, '0')); | |
const [fg, bg] = mapping[method]; | |
const prefix = `${fg}[${pkg.name}] ${getDate()} ${bg}${ | |
colors.fg.white | |
}${method.toUpperCase()}${colors.reset}`; | |
oldMethod.apply(console, [ | |
prefix, | |
...args.map((arg) => { | |
if (arg instanceof Error) throw arg; | |
return `${typeof arg === 'string' ? arg : JSON.stringify(arg)}`; | |
}), | |
]); | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment