如何存储标准输出的结果?

时间:2017-05-22 08:31:21

标签: javascript string unix meteor client-server

我执行UNIX命令列出所有以.svg结尾的文件

'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出了什么问题?为什么我无法从客户端访问它,尽管它是一个字符串?我认为错误是在服务器上,所以你能帮我找到它吗?

2 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分: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);
 }   
}