Skip to content

Commit

Permalink
Return error instead of killing process
Browse files Browse the repository at this point in the history
  • Loading branch information
vvakar committed Jul 8, 2024
1 parent 0215411 commit 3c39d18
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
15 changes: 14 additions & 1 deletion examples/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,17 @@ export default function () {
console.log(exec.command("ls",["-a","-l"], {
"dir": "sub-directory" // optional directory in which the command has to be run
}));
}


// With custom error handling
try {
var output = exec.command("ls",["-a", "NO_SUCH_DIR"], {
"continue_on_error": true
});
} catch (e) {
console.log("ERROR: " + e);
if (e.value && e.value.stderr) {
console.log("STDERR: " + String.fromCharCode.apply(null, e.value.stderr))
}
}
}
11 changes: 7 additions & 4 deletions exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ type EXEC struct {

// CommandOptions contains the options that can be passed to command.
type CommandOptions struct {
Dir string
Dir string
ContinueOnError bool
}

// Ensure the interfaces are implemented correctly.
Expand All @@ -46,14 +47,16 @@ func (exec *EXEC) Exports() modules.Exports {
}

// Command is a wrapper for Go exec.Command
func (*EXEC) Command(name string, args []string, option CommandOptions) string {
func (*EXEC) Command(name string, args []string, option CommandOptions) (string, error) {
cmd := exec.Command(name, args...)
if option.Dir != "" {
cmd.Dir = option.Dir
}

out, err := cmd.Output()
if err != nil {
if err != nil && !option.ContinueOnError {
log.Fatal(err.Error() + " on command: " + name + " " + strings.Join(args, " "))
}
return string(out)

return string(out), err
}

0 comments on commit 3c39d18

Please sign in to comment.