最近正在与casperjs一起玩,并且没有设法完成以下代码,正在使用child_process,需要获取函数输出以将其传递给另一个函数吗?
成功调用变量范围仅限于成功函数,我无法在代码中的任何地方使用它
casper.repeat(3, function() {
this.sendKeys(x('//*[@id="text-area"]'), testvalue.call(this)); // testvalue.call(this) dosnt input anything here
})
casper.echo(testvalue.call(this)); // Print output successfully
function testvalue() {
var spawn = require("child_process").spawn
var execFile = require("child_process").execFile
var child = spawn("/usr/bin/php", ["script.php"])
child.stdout.on("data", function (data) {
console.log(JSON.stringify(data)); // Print output successfully
return JSON.stringify(data); // Problem is here i cant use Data any where in code except this scope
})
}
由于spawn
是异步过程,因此需要使用的回调testvalue
。在事件处理程序中返回内容不会从中返回testvalue
。
另一个问题是您需要保留在CasperJS控制流中。这就是为什么我testvaluedone
用来确定生成的进程是否已经执行完毕并且可以的原因completeData
。
casper.repeat(3, function() {
var testvaluedone = false;
var completeData = "";
testvalue();
this.waitFor(function check(){
return testvaluedone;
}, function then(){
this.sendKeys(x('//*[@id="text-area"]'), completeData);
}); // maybe tweak the timeout a little
});
var testvaluedone, completeData;
function testvalue() {
var spawn = require("child_process").spawn;
var execFile = require("child_process").execFile;
var child = spawn("/usr/bin/php", ["script.php"]);
child.stdout.on("data", function (data) {
completeData += JSON.stringify(data);
});
child.on("exit", function(code){
testvaluedone = true;
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句