add node command

This commit is contained in:
Shane C 2024-07-05 11:28:33 -04:00
parent c7b6273166
commit cafa0dcca1
Signed by: shane
GPG key ID: E46B5FEA35B22FF9
2 changed files with 39 additions and 1 deletions

38
cmd/node.go Normal file
View file

@ -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
}

View file

@ -9,7 +9,7 @@ import (
var ErrNotFound = errors.New("which: command not found") 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) command := exec.Command("which", cmd)