Meteor:执行shell的调用方法(clone git repo)
问题:
在Meteor中,如何从客户端调用方法(传递名称),让服务器执行一些shell命令? 方法函数基本上是:创建一个目录,然后克隆具有给定名称的git repo. 这是非常简单的东西,但Meteor不会这样做.我已经圈了好几个小时了.一切都在普通的bash或节点中工作.在那一刻: 目录已创建 – >服务器重新启动 – > meteor抛出一个错误,声称该目录已经存在 – > meteor删除目录 – >服务器重启 码: var cmd,exec,fs; if (Meteor.isClient) { Template.app.events({ 'click button': function() { Meteor.call('clone',"NAMEHERE",function(error,result) { if (error) { console.log(error); } else { console.log(result); } }); } }); } if (Meteor.isServer) { fs = Npm.require('fs'); exec = Npm.require('child_process').exec; cmd = Meteor.wrapAsync(exec); Meteor.methods({ 'clone': function(name) { var dir; dir = process.env.PWD + "/projects/" + name; cmd("mkdir " + dir + "; git clone git@gitlab.com:username/" + name + ".git " + dir,Meteor.bindEnvironment(function(error,stdout,stderr) { if (error) { throw new Meteor.Error('error...'); } else { console.log('done'); } })); return 'cloning...'; } }); } 更新1 如果我事先手动创建文件夹,以下代码将成功克隆repo: if (Meteor.isClient) { Template.all.events({ 'click button': function() { Meteor.call('clone',this.name); } }); } if (Meteor.isServer) { exec = Npm.require('child_process').exec; cmd = Meteor.wrapAsync(exec); Meteor.methods({ 'clone': function(name) { var dir,res; dir = process.env.PWD + "/projects/" + name; res = cmd(git clone git@gitlab.com:username/" + name + ".git " + dir); return res; } }); } 但是,如果我将“mkdir”目录添加到cmd,我仍然遇到同样的问题: 目录已创建 – >服务器重新启动 – > meteor抛出一个错误,声称该目录已经存在 – > meteor删除目录 – >服务器重启 解: Meteor正在重新启动,因为其目录中的某些内容已更改(项目).然后在启动时重新运行该方法.这是方法调用的一个单独问题. 来自update 1 / @ Rebolon的答案的代码是解决方案. 解决方法
你的Meteor.call没问题,问题似乎在服务器端:
你正确使用wrapAsync打包exec npm对象,但是你误用了cmd var:你只需要发送一个这样的参数: var res = cmd("mkdir " + dir + "; git clone git@gitlab.com:username/" + name + ".git " + dir); return res; 实际上你的代码显示你想要返回客户端的不同信息: >我收到了电话,命令正在等待中 但实际上它无法工作,因为wrapAsync cmd(…)将等到它完成后再返回“待定…” 您是否真的需要通知客户端该命令正在等待,然后它已完成?如果是,您可以使用状态集合,您可以在其中存储命令的状态(已接收/待处理/确定/错误…),然后在您的方法中,您只需更新集合,并在您的客户端只需订阅此状态集合. 您可以查看这个项目,我在服务器上使用exec(带有重试包)和一个用于管理挂起状态的集合:https://github.com/MeteorLyon/satis-easy (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |