1

I try to execute some commands (inside config.json) Only npm commands have display output

This is my first time using Stackoverflow Please forgive me if I did not do well

expected result: when i write any command in config.json will output the correct result

main.go

func main () {
    file, _ := os.Open("config.json")
    byteres, _ := ioutil.ReadAll(file)
    var config Config
    json.Unmarshal(byteres, &config)
    defer file.Close()

    process := exec.Command(config.StartCommand)
    stdout, _ := process.StdoutPipe()
    processscanner := bufio.NewScanner(stdout)
    processscanner.Split(bufio.ScanLines)

    process.Start()
    go func() {
        for processscanner.Scan() {
            message := processscanner.Text()
            fmt.Println(message)
        }
    }()
}

config.json

{
    "StartCommand": "npm"
}
MoMuAlt
  • 21
  • 3
  • Wait for your process to end. Your program exits before it can read the output. – Burak Serdar Dec 31 '22 at 03:00
  • Don't ignore errors. Your config file could not be readable, the json could be malformatted. You may not be able to get the StdoutPipe. you may not be able to start the command. In all of these cases, you are ignoring the error return value. And this would tell you important information. – Erwin Bolwidt Dec 31 '22 at 04:40
  • If all you want to do is copy the output unmodified, you can simplify to `process.Stdout = os.Stdout; err := process.Run()` (instead of using the scanner). – Peter Dec 31 '22 at 10:44

1 Answers1

0

Your main function isn't waiting for your goroutine to finish. Use sync.WaitGroup to block main until the goroutine is done.

Dan
  • 179
  • 1
  • 1
  • 13