When using exec.Command
to run another command that outputs color, e.g.
func main() {
c := exec.Command("node-gyp", "rebuild")
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
c.Run()
}
this works as expected and outputs colored text to the terminal, e.g:
However, consider if we wanted to to also capture the output stream for later use. We could do something like this (the colored output is on stderr):
func main() {
c := exec.Command("node-gyp", "rebuild")
c.Stdin = os.Stdin
c.Stdout = os.Stdout
var buf bytes.Buffer
c.Stderr = io.MultiWriter(os.Stderr, &buf)
c.Run()
// do something with buf
}
Now, everything is in black and white:
This prompts two questions:
- What's going on here? How can the simple act of essentially doing a
tee
on a Writer stream cause the terminal colors (which I'm guessing are UTF-8 symbols) to disappear? - If you use
exec.Command("ls", "--color")
instead, colors show up in both instances. Why do the colors work here and not fornode-gyp rebuild
? If they're encoded differently, what's the difference?