我试图在Meteor方法中使用child_process.spawn()
。我想从外部进程捕获PID,stdout,stderr和退出代码,并将所有内容存储在数据库中。
在我添加第一个insert()
电话之前,一切正常。使用insert()
,只有一个“假”'文档被插入到数据库中。我在服务器控制台中没有收到任何错误消息。如果我先注释掉insert()
,那么其他insert()
次来电就会成功。
// server/app.js
var spawn = Npm.require('child_process').spawn;
Meteor.methods({
start: function() {
var child = spawn('ls', ['/tmp']);
var pid = child.pid;
var wrappedChildStdoutOn = Meteor.wrapAsync(child.stdout.on, child.stdout);
var wrappedChildStderrOn = Meteor.wrapAsync(child.stderr.on, child.stderr);
var wrappedChildOn = Meteor.wrapAsync(child.on, child);
// this insert() breaks upcoming insert() calls!
Stuff.insert({pid: pid, date: new Date(), type: 'dummy', data: 'dummy'});
wrappedChildStdoutOn('data', function (data) {
Stuff.insert({pid: pid, date: new Date(), type: 'stdout', data: data.toString()});
});
wrappedChildStderrOn('data', function (data) {
Stuff.insert({pid: pid, date: new Date(), type: 'stderr', data: data.toString()});
});
wrappedChildOn('exit', function (code) {
Stuff.insert({pid: pid, date: new Date(), type: 'exit', code: code});
});
}
});
第一次insert()
来电是什么?
答案 0 :(得分:1)
insert
需要一些时间,因此ls
在insert
完成之前完成输出。当你把事件处理程序放到位时,为时已晚。
您可以通过将第一个insert
移至最后,在insert
来电前移动第一个spawn
或添加无操作function () {}
回调来解决问题到insert
所以它被称为异步。