由于最近的项目需求,须要在 Electron 客户端启动的时候启动 nginx 服务,因此研究了一下怎么在 Electron 调用 命令行。 由于 Electron 基于 Chromium 和 Node.js,能够直接使用 Node.js 的 API 和一些包。目前研究有如下两种方法:html
child_process 是 Node.js 的内置模块,该模块提供了衍生子进程的能力。node
实现代码:nginx
const exec = require('child_process').exec
export function start () {
// 任何你指望执行的cmd命令,ls均可以
let cmdStr1 = 'your command code'
let cmdPath = './file/'
// 子进程名称
let workerProcess
runExec(cmdStr1)
function runExec (cmdStr) {
workerProcess = exec(cmdStr, { cwd: cmdPath })
// 打印正常的后台可执行程序输出
workerProcess.stdout.on('data', function (data) {
console.log('stdout: ' + data)
})
// 打印错误的后台可执行程序输出
workerProcess.stderr.on('data', function (data) {
console.log('stderr: ' + data)
})
// 退出以后的输出
workerProcess.on('close', function (code) {
console.log('out code:' + code)
})
}
}
复制代码
node-cmd 是 一个让 Node.js 调用命令行的包。git
首先咱们须要安装:github
npm install node-cmd --save
npm
实现代码:api
var cmd=require('node-cmd');
cmd.get(
'pwd',
function(err, data, stderr){
console.log('the current working dir is : ',data)
}
);
cmd.run('touch example.created.file');
cmd.get(
'ls',
function(err, data, stderr){
console.log('the current dir contains these files :\n\n',data)
}
);
cmd.get(
`
git clone https://github.com/RIAEvangelist/node-cmd.git
cd node-cmd
ls
`,
function(err, data, stderr){
if (!err) {
console.log('the node-cmd cloned dir contains these files :\n\n',data)
} else {
console.log('error', err)
}
}
);
复制代码
以上就是两种在 Electron 中调用命令行的方法,其实都是借助了 Node.js的能力。bash
他们二者的区别是 child_process 能够指定命令执行的路径,默认项目根目录;而 node-cmd 不能指定执行路径,只能本身 cd 到目标路径。ui
我是使用的 child_process,具体使用场景还须要根据本身的需求来。spa