From cafa0dcca17d2b02b86ee565b619f28a8a5e29c8 Mon Sep 17 00:00:00 2001 From: Shane C Date: Fri, 5 Jul 2024 11:28:33 -0400 Subject: [PATCH] add node command --- cmd/node.go | 38 ++++++++++++++++++++++++++++++++++++++ cmd/which.go | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 cmd/node.go diff --git a/cmd/node.go b/cmd/node.go new file mode 100644 index 0000000..2e57784 --- /dev/null +++ b/cmd/node.go @@ -0,0 +1,38 @@ +package cmd + +import ( + "errors" + "fmt" + "os/exec" + "strings" +) + +var NodeNotFound = errors.New("nodejs not found") + +func Node(args ...string) (output string, err error) { + + if _, err := Which("node"); err != nil { + if errors.Is(err, ErrNotFound) { + return "", NodeNotFound + } else { + return "", err + } + } + + command := exec.Command("node", args...) + + outputBytes, err := command.Output() + if err != nil { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + if exitErr.ExitCode() == 1 { + return "", ErrNotFound + } else { + return "", fmt.Errorf("command error: %w", err) + } + } + } + + return strings.Trim(string(outputBytes), "\n"), nil + +} diff --git a/cmd/which.go b/cmd/which.go index c7acd6a..b66eafc 100644 --- a/cmd/which.go +++ b/cmd/which.go @@ -9,7 +9,7 @@ import ( var ErrNotFound = errors.New("which: command not found") -func Which(cmd string) (string, error) { +func Which(cmd string) (dir string, err error) { command := exec.Command("which", cmd)