grafana / xk6-exec

A k6 extension for running external commands.
Apache License 2.0
20 stars 21 forks source link

CLI commands do not work on Windows machine #2

Open abal3 opened 2 years ago

abal3 commented 2 years ago

When running the CLI commands e.g. console.log(exec.command("date")); nothing is outputted to the console. No errors are thrown either.

amommersteeg-d2l commented 1 year ago

So there is a something strange when using this extension with Windows. I have noticed that the command runs/works but return nothing to the k6 terminal, just an empty line, like \n was printed.

I believe by default cmd is used to run commands. You can force it run as powershell console.log(exec.command("'powershell" ["date"]));

Anyways to overcome the issues with Windows I ended modifying this extension to use go-cmd using their buffer code example to return stdout and stderr. Disclaimer: I am new to go-lang & xk6-extensions

package cmd

import (
    "os"
    "fmt"
    "strings"

    "github.com/go-cmd/cmd"
    "go.k6.io/k6/js/modules"
)

func init() {
    modules.Register("k6/x/cmd", new(CombinedOutput))
}

type CombinedOutput struct{
    Stdout string
    Stderr string
}

func (c *CombinedOutput) RunCmd(name string, args []string) bool {

    envCmd := cmd.NewCmd(name, args...)
    status := <-envCmd.Start()

    c.Stdout = strings.Join(status.Stdout, "\n")
    c.Stderr = strings.Join(status.Stderr, "\n")

    if envCmd.Status().Error != nil || len(status.Stderr) > 0{
        return false
    }else{
        return true
    }
}