英文:
How to pipe npm install progress bar to the terminal in go?
问题
我已经尝试使用stdoutpipe和stderrpipe,如下所示。
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)
}
然而,我只得到以下输出:
added 87 packages, and audited 88 packages in 3s
9 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
我该如何获得在控制台运行npm install时显示的安装进度条?
我还尝试了以下解决方案,并在运行shell.run()后打印缓冲区,但它也给出了与上面相同的输出。
shell := exec.Command(command, args...)
shell.Dir = cwd
var stderr, stdout bytes.Buffer
shell.Stderr = &stderr
shell.Stdout = &stdout
return shell, &stdout, &stderr
英文:
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
答案1
得分: 1
已解决,感谢@Adrian的评论
cmd := exec.Command("npm", args...)
cmd.Dir = cwd
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
将输出重定向到os的标准输出和标准错误就是解决的关键。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论