Node.js执行shell
child_process
(原生)
Nodejs 下引入模块 child_process
实现调用 shell
调用的两种方式
1
2
child_process.exec(command[, options][, callback])
child_process.execFile(file[, args][, options][, callback])
Nodejs 中通过 exec 执行 shell 脚本,并打印查询到的信息
1
2
3
4
5
Explainvar child = require('child_process');
child.exec('ls', function(err, sto) {
console.log(sto);//sto才是真正的输出,要不要打印到控制台,由你自己啊
})
执行文件
1
2
const exec = require('child_process').execSync
exec('bash ./shell/shell1.sh hello')
对应的 shell 文件
1
2
3
#!/bin/bash
# This is our first script.
echo "$1" > log.txt
示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const util = require('util');
const path = require('path');
const child_process = require('child_process');
// 调用util.promisify方法,返回一个promise,如const { stdout, stderr } = await exec('rm -rf build')
const exec = util.promisify(child_process.exec);
const appPath = path.join(__dirname, 'app');
const runClean = async function () {
// cwd指定子进程的当前工作目录 这里的rm -rf build为删除指定目录下的一个文件夹
await exec(`rm -rf build`, {
cwd: appPath
});
await exec(`rm -rf test`, {
cwd: appPath
});
}
runClean();
注意
util.promisify 是在 node.js 8.x 版本中新增的一个工具,用于将老式的 Error first callback 转换为 Promise 对象,让老项目改造变得更为轻松。
shelljs(三方)
shelljs 是 j 基于 nodeAPI 的一个扩展,要引入插件:(npm地址);
它比原生的 child_process 的兼容性更好,使用更灵活,这个插件的使用率很高。
simple-git(GIT)
执行 shell 脚本操作 git,其实对于复杂的 git 命令语句,写起来还是很不方便,最后介绍一个专为 git 设计的插件:simple-git(npm地址)
- 在项目中引入插件后,调用 simple-git/promise 可执行异步 git 操作,方便结合 async/await 使用
- 它封装并支持了很多 git 的方法,比如 clone、commit、status、pull 等等,将 cmd 命令和参数,传入即可
- 甚至可以用 git.raw(),解析前端输入的 git 命令
本文由作者按照 CC BY 4.0 进行授权