exec
# sync
# Node.js
const { execSync } = require("child_process");
const output = execSync(`echo 'hello world'`);
console.log(output.toString());
1
2
3
4
5
2
3
4
5
Output
hello world
1
# Go
package main
import (
"fmt"
"os/exec"
)
func main() {
output, err := exec.Command("echo", "hello world").Output()
if err != nil {
panic(err)
}
fmt.Println(string(output))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Output
hello world
1
# async
# Node.js
const { exec } = require("child_process");
exec(`echo 'hello world'`, (error, stdout, stderr) => {
if (error) {
console.error(err);
}
if (stderr) {
console.error(stderr);
}
if (stdout) {
console.log(stdout);
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Output
hello world
1
# Go
package main
import (
"os"
"os/exec"
)
func main() {
cmd := exec.Command("echo", "hello world")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
Output
hello world
1
编辑 (opens new window)
上次更新: 2022/09/30, 11:34:22