dop251 / goja_nodejs

Nodejs compatibility library for Goja
MIT License
329 stars 78 forks source link

console: Allow configuring custom output for console #15

Closed nwidger closed 4 years ago

nwidger commented 4 years ago

Allow configuring where console commands print to with the addition of a new RequireWithPrinter(Printer) function which returns a require.ModuleLoader that loads a console command into the given runtime which writes to the supplied Printer.

Printer is a new interface type with a single method, Print(string). A new private printer field has been added to the Console type, and (c *Console).log now calls c.printer.Print to print the final string after formatting its arguments. A helper type PrinterFunc can be used to create a Printer from a function with signature func(string).

If a custom Printer is not given, a default Printer is used which passes its string argument unmodified to log.Print, thus preserving the existing behavior.

Added a new test TestConsoleWithPrinter which ensures that the console command functions correctly when loaded into a runtime using RequireWithPrinter and a custom Printer.

nwidger commented 4 years ago

@dop251 One question I had for this one was whether it would be worth complicating the Printer interface such that the printer could know which console command the message came from. I played around with making it

type Printer interface {
    Print(kind, msg string)
}

where kind would be one of log, error or warn. This would allow a printer to, for example, send log/warn messages to stdout and error messages to stderr. I could go either way, however, what do you think?

dop251 commented 4 years ago

I'd probably split it into separate methods:

type ConsolePrinter interface {
       Log(string)
       Warn(string)
       Error(string)
}
nwidger commented 4 years ago

@dop251 Works for me, I've updated the PR with those changes.