Last active
July 25, 2024 15:24
-
-
Save Rettend/474d717f2cc9006f8da82bef282a9551 to your computer and use it in GitHub Desktop.
Allows chaining console logs to print them to the same line
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 process from 'node:process' | |
class ChainableConsole extends console.Console { | |
#chain: this | |
#isChaining: boolean = false | |
#isFirstInChain: boolean = true | |
constructor(stdout: NodeJS.WriteStream, stderr: NodeJS.WriteStream, ignoreErrors?: boolean) { | |
super(stdout, stderr, ignoreErrors) | |
this.#chain = this.createChain() | |
} | |
createChain() { | |
return new Proxy(this, { | |
get: (target, prop: string) => { | |
if (typeof target[prop as keyof this] === 'function') { | |
return (...args: any[]) => { | |
if (this.#isChaining && !this.#isFirstInChain) | |
process.stdout.write(' '); | |
(target[prop as keyof this] as (...args: any[]) => this)(...args) | |
this.#isFirstInChain = false | |
return this.#chain | |
} | |
} | |
return target[prop as keyof this] | |
}, | |
}) | |
} | |
chain(callback: (c: this) => void) { | |
this.#isChaining = true | |
this.#isFirstInChain = true | |
callback(this.#chain) | |
this.#isChaining = false | |
process.stdout.write('\n') | |
return this | |
} | |
override log(...args: any[]) { | |
if (this.#isChaining) | |
process.stdout.write(args.join(' ')) | |
else | |
super.log(...args) | |
return this | |
} | |
// Create custom log methods like this, maybe even use chalk | |
shout(...args: any[]) { | |
const upperArgs = args.map(arg => arg.toString().toUpperCase()) | |
this.log(...upperArgs) | |
return this | |
} | |
} | |
const c = new ChainableConsole(process.stdout, process.stderr) | |
// Usage | |
console.shout('asd') | |
console.chain(c => c.log('asd').log('fgh')) | |
console.chain(c => c | |
.log('asd') | |
.shout('asd') | |
.log('fgh') | |
.shout('fgh'), | |
) | |
// Output | |
// ASD | |
// asd fgh | |
// asd ASD fgh FGH | |
export { c as console } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment