Home > database >  How to pipe npm install progress bar to the terminal in go?
How to pipe npm install progress bar to the terminal in go?

Time:11-18

I have tried using stdoutpipe and stderrpipe like shown below.

shell := exec.Command("npm", args...)
shell.Dir = cwd

outpipe, _ := shell.StdoutPipe()
errpipe, _ := shell.StderrPipe()

shell.Start()

go func(pipe io.ReadCloser) {
    reader := bufio.NewReader(pipe)
    line, err := reader.ReadString('\n')

    for err == nil {
        fmt.Println(string(line))
        line, err = reader.ReadString('\n')
    }

    fmt.Println("exited")

}(outpipe)

go func(pipe io.ReadCloser) {

    reader := bufio.NewReader(pipe)
    line, err := reader.ReadString('\n')

    for err == nil {
        fmt.Println(string(line))
        line, err = reader.ReadString('\n')
    }

    fmt.Println("exited")

}(errpipe)

err := shell.Wait()

if err != nil {
    fmt.Println(err)
}

However I only get output:

added 87 packages, and audited 88 packages in 3s



9 packages are looking for funding

run `npm fund` for details



found 0 vulnerabilities

How do I get the installation progress bar that you get when you run npm install from the console?

I have also tried using a solution like below and printing the buffer after running shell.run() but it also gives the same output as the one above.

shell := exec.Command(command, args...)
shell.Dir = cwd
var stderr, stdout bytes.Buffer

shell.Stderr = &stderr
shell.Stdout = &stdout

return shell, &stdout, &stderr

CodePudding user response:

Solved thanks @Adrian's comment

cmd := exec.Command("npm", args...)
cmd.Dir = cwd

cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

Redirecting to os's stdout and stderr is what did the trick.

  • Related