nodejs中执行Shell命令(koa+vue)

nodejs中怎么执行系统命令或者linux命令来完成一些功能呢?

假设有这样一个需求,在页面中,点击按钮重启服务,升级系统之类的,服务是部署在linux下的C++项目。需要发送请求到web后台,web后台中来执行Linux命令实现重启或者升级服务的功能。刚好在工作中遇到了这样的问题,做一个简要记录。
先查了一部分资料 http://nodejs.cn/api/child_process.html
nodejs可以利用子进程来调用系统命令或者文件,提供了与系统交互的重要接口。在上面的文档中有较为详细的说明。
这里主要用到的是
1 child_process.exec(command[, options][, callback])

 

首先需要安装一下
npm install child_process --save

先是前端的页面和逻辑

vue项目,使用了element-ui
<el-button class="btn" size="mini" type="primary"@click="RestartServer">重启服务</el-button>
js部分的methods中加一个对应的方法RestartServer(),点击按钮发送请求
RestartVIServer(){
  var _this=this;
  _this.loading=true;
  this.$axios.get("action/OwnRestartServer").then(res=>{
    let data=res.data;
      _this.$message({
        type: 'success',
        message: "操作成功!系统正在重启,请稍等1-2分钟后刷新页面",
        duration:5000,
        showClose: true
      });	
  }).catch(err=>{
    _this.$message({
      type: 'error',
      message: err,
      showClose: true
    });	
  })
},

 

nodeJS ----web后台

话不多说,直接上代码
const Koa=require("koa");
const router=require("koa-router")();
const exec=require('child_process').exec;
let reStartPro="sudo monit restart OwnServer";//这是一条重启服务的linux命令,也可以是执行其他功能的命令~

//对exec进行一个简单的封装,返回的是一个Promise对象,便于处理。
function doShellCmd(cmd){
    let str=cmd;
    let result={};
    return new Promise(function(resolve,reject){
        exec(str,function(err,stdout,stderr){
            if(err){
                console.log('err');
                result.errCode=500;
                result.data="操作失败!请重试";
                reject(result);
            }else{
                console.log('stdout ',stdout);//标准输出
                result.errCode=200;
                result.data="操作成功!";
                resolve(result);
            }
        })
    })
}
//加URL
router.get('action/OwnRestartServer', async (ctx, next) => {
    let result=await doShellCmd(reStartPro);//调用exec
    console.log("[restartServer] ",result);
    ctx.response.status=result.errCode;
    ctx.response.body=result.data;
});
app.use(router.routes());
app.listen(3000);
console.log('app started at port 3000...');
这样在点击重启服务按钮后,会发送127.0.0.1:3000/action/OwnRestartServer请求到web后台,web后台执行Linux命令完成需求功能。
 

原创文章,转载请注明出处~~~



posted @ 2019-06-28 18:25  想飞高的菜鸟  阅读(3277)  评论(0编辑  收藏  举报