在electron中調(diào)用cmd命令,可以通過(guò)node-cmd來(lái)實(shí)現(xiàn):
安裝node-cmd模塊
npm install node-cmd
安裝完成后,可以通過(guò)兩種方式來(lái)調(diào)用
1)將node-cmd定義為插件,通過(guò)插件進(jìn)行調(diào)用,如果應(yīng)用有多個(gè)頁(yè)面需要調(diào)用到cmd,可以通過(guò)插件方式
在renderer下新建plugins/cmd/index.js
/**
* 自定義cmd插件
* @author LiQun
* @date 2019/4/14
*/
const cmdPlugin = {
install (Vue) {
Vue.prototype.$cmd = require('node-cmd')
}
}
export default cmdPlugin
在main.js中添加插件
import cmd from './plugins/cmd/index'
Vue.use(cmd)
需要調(diào)用的頁(yè)面
<template>
<div style="margin-top: 50px;">
<button @click="testCmd">testCmd</button>
</div>
</template>
<script>
/**
* 測(cè)試頁(yè)面
* @author LiQun
* @date 2019/3/25
*/
export default {
name: 'home',
data () {
return {}
},
methods: {
testCmd () {
this.$cmd.get(
`
ls
`,
function (err, data, stderr) {
console.log(stderr)
if (!err) {
console.log('the node-cmd cloned dir contains these files :\n\n', data)
} else {
console.log('error', err)
}
}
)
}
},
computed: {},
mounted () {
console.log(this.$electron)
}
}
</script>
<style scoped lang="scss">
</style>
2)頁(yè)面直接調(diào)用,html部分相同,不再額外列舉:
<script>
const cmd = require('node-cmd')
/**
* 測(cè)試頁(yè)面
* @author LiQun
* @date 2019/3/25
*/
export default {
name: 'home',
data () {
return {}
},
methods: {
testCmd () {
cmd.get(
`
ls
`,
function (err, data, stderr) {
console.log(stderr)
if (!err) {
console.log('the node-cmd cloned dir contains these files :\n\n', data)
} else {
console.log('error', err)
}
}
)
}
},
computed: {},
mounted () {
console.log(this.$electron)
}
}
</script>
結(jié)果:

結(jié)果