2017-05-22 130 views
0

我做了UNIX命令列出我的所有文件与.svg这样如何存储stdout的结果?

'getExistingFiles': function() { 
var list =""; 
child = exec_tool('cd /home/me/files/; ls *.svg', 
      function (error, stdout, stderr) { 
      list = stdout; 
      console.log(typeof list); 
      console.log("LIST:------------"); 
      console.log(list); 
      return list; 
      if (error !== null) { 
       console.log('exec error: ' + error); 
       list = "error: " + error; 
       return list; 
      }else{ 
       console.log("Listing done"); 
      } 
      }); 
} 

结束我有一个结果:

string 
LIST:------------ 
test.svg 
output.svg 
test2.svg 

然后用JavaScript我要为每个文件创建一个新元素那就是在list,但我不能回到我的list我总是得到“未定义”

enter image description here

那么我的list有什么问题?为什么我不能从客户端访问它,尽管它是一个字符串?我认为错误在服务器上,那么你能帮我找到它吗?

+1

显示getExistingFiles法的源代码,请。 – iiro

+0

@iiro这是帖子上的代码(第一个代码块) – Jerome

回答

2

看看这是否适合你。使用光纤/未来的异步功能。如果遇到问题,我们来调整它。

Server.js

// 
    // Load future from fibers 
    var Future = Npm.require("fibers/future"); 
    // Load exec 
    var exec = Npm.require("child_process").exec; 

    Meteor.methods({ 
    runListCommand: function() { 
     // This method call won't return immediately, it will wait for the 
     // asynchronous code to finish, so we call unblock to allow this client 
     // to queue other method calls (see Meteor docs) 
     this.unblock(); 
     var future=new Future(); 
     var command="cd /home/me/files/; ls *.svg"; 
     exec(command,function(error,stdout,stderr){ 
     if(error){ 
      console.log(error); 
      throw new Meteor.Error(500,command+" failed"); 
     } 
     future.return(stdout.toString()); 
     }); 
     return future.wait(); 
    } 
    }); 

Client.js:

Meteor.call('runListCommand', function (err, response) { 
    console.log(response); 
}); 
+0

它会起作用,我测试了它。谢谢 ! – Jerome

1

这是因为exec_tool是一个异步函数?

尝试wrapAsync,有点像这样。从docs查看更多内容。

'getExistingFiles': function() { 
var list =""; 
var et = Meteor.wrapAsync(exec_tool); 

try { 
    child = et('cd /home/me/files/; ls *.svg'); 
    return child.stdout; 
} catch (err) { 
    throw new Meteor.Error(err, err.stack); 
} 
} 
+0

我仍然在客户端上有'undefined' – Jerome

+0

为什么你做了同样的问题? http://stackoverflow.com/questions/44110441/how-to-return-a-sdtout-from-a-server-to-a-client-inside-a-string – iiro

+0

我想做一个新的比这更清晰一个 – Jerome