【笔记】Nodejs执行Shell命令

前言

Nodejs执行Shell命令

当前进程执行Shell命令

1
2
3
4
5
const { exec } = require("child_process");

exec("ls", "-l", function (error, stdout, stderr) {
...
});

子进程执行Shell命令

{}:第三个参数是其他选项

cwd: "":当前命令执行的工作目录
env: {}:临时使用的系统环境变量
shell: true:是否通过Shell执行命令
detached: true:子进程脱离父进程独立执行
timeout: 0:超时时间,单位毫秒

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const { spawn } = require("child_process");

const childProcess = spawn("ls", "-l");
// const childProcess = spawn("ls", "-l", { shell: true });

childProcess.stdout.on("data", function (data) {
...
});
childProcess.stderr.on("data", function (data) {
...
});
childProcess.on("close", function (code) {
...
});
1
2
3
4
5
6
7
8
9
const { spawn } = require("child_process");

const childProcess = spawn("ls", "-l");

childProcess.stdout.pipe(process.stdout);
childProcess.stderr.pipe(process.stderr);
childProcess.on("close", function () {
...
});

执行可执行文件

1
2
3
4
5
const { execFile } = require("child_process");

execFile("exe", ["--version"], (error, stdout, stderr) => {
...
});

完成