How to store the result of a stdout? [duplicate]

丶灬走出姿态 提交于 2019-12-25 05:21:10

问题


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

I have a result:

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

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 ?


回答1:


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



回答2:


It's because exec_tool is a async function?

Try wrapAsync, somethign like this. See more from 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);
 }   
}


来源:https://stackoverflow.com/questions/44108142/how-to-store-the-result-of-a-stdout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!