如何存储标准输出的结果? [英] How to store the result of a stdout?

查看:77
本文介绍了如何存储标准输出的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I do a UNIX command to list all my files that ends with .svg like this

'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我要为列表中的每个文件创建一个新元素但我无法返回我的列表我总是得到未定义

then with JavaScript I want to create a new element for each file that is in the list but I can't return my list I always got "undefined"

那么我的列表怎么了?为什么我不能从客户端访问它,尽管它是一个字符串?我认为错误是在服务器上的,所以您能帮我找到它吗?

So what is wrong with my list ? Why I can't access it from the client despite it's a string ? I think the error is on the server so could you help me to find it ?

推荐答案

看看这是否对您有用。使用光纤/期货的异步功能。让我们对此进行调整,以防遇到问题。

See if this works for you. Async function using fiber/future. Let's tweak this in case you run into issues.

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);
});

这篇关于如何存储标准输出的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆