如何将sdtout从服务器返回到字符串中的客户端? [英] How to return a sdtout from a server to a client inside a string?
问题描述
我正在尝试返回我的方法的 stdout
,但在客户端我总是有 undefined
尽管服务器说它是带有内容的字符串
。
I'm trying to return the stdout
of my method but on the client I always have undefined
despite the server says it's a string
with content.
我这样做:
'getExistingFiles': function () {
var list = "";
return new Promise(Meteor.bindEnvironment(function(resolve) {
child = exec_tool("ls -al",
function (error, stdout, stderr) {
if (error !== null) {
console.error('exec error: ' + error);
list = "error: " + error;
resolve(list);
return list;
}else{
list = stdout;
console.log(typeof list);
console.log("LIST:------------");
console.log(list);
resolve(list);
return list;
}
});
}));
}
在我的终端上我有日志:
On my terminal I have the logs:
但是当我尝试访问该值时客户端 undefined
:
But on the client when I try to access the value it's undefined
:
Meteor.call("getExistingFiles",function(list){
console.log(list);
console.log(typeof list);
});
所以我的问题是,我怎么能发送这个列表
给客户?
So my question is, how could I send this list
to the client ?
我试过这样测试一下我的客户是不是错了,但是我认为服务器上没有它
I tried like this to test if it was my client who was wrong but no it's on the server I think
//server
var et = Meteor.wrapAsync(exec_tool);
try {
child = et('ls -al');
console.log("LIST:------------");
console.log(child);
console.log(typeof child);
return child;
} catch (err) {
throw new Meteor.Error(err, err.stack);
}
即使这样它也会发送 undefined
为什么?!
even like this it send a undefined
WHY ?!
var et = Meteor.wrapAsync(exec_tool);
try {
var proc = exec_tool("ls -al")
proc.stdout.on('data', function (data) {
//do something with data
console.log(data);
list = list + data;
});
proc.stdout.on('end', function() {
console.log("end");
console.log(list);
return list;
});
} catch (err) {
throw new Meteor.Error(err, err.stack);
}
推荐答案
在服务器上(承诺来自评估服务器,然后在完成后发送给客户端:
On the server (promises from the server are evaluated and then sent to the client when they're done):
getExistingFiles: function () {
return new Promise((resolve, reject) => {
child = exec_tool("ls -al",
function (error, stdout, stderr) {
if (error) {
reject(error);
} else {
resolve(stdout);
}
});
}));
}
在客户端:
Meteor.call("getExistingFiles", function(err, list) {
if(err) {
// handle your error
throw err;
}
console.log(list);
});
承诺没有返回
。来自异步函数的回调通常具有函数(错误,结果)
参数列表。所以,想要的结果应该在第二个参数中。试试这样。
Promises don't have return
. Callbacks from async functions usually have the function (error, result)
argument list. So, the wanted result should be in the second argument. Try it like this.
这篇关于如何将sdtout从服务器返回到字符串中的客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!