2015-07-10 62 views
-1

我從客戶端調用服務器功能,執行UNIX命令並獲得服務器上的輸出,但我需要將結果返回給調用它的客戶端功能。我在服務器上得到輸出,但Meteor.call立即返回結果undefined,bc exec命令需要一些時間才能運行。任何建議如何延遲獲得結果和繞過這個問題?返回從服務器到客戶端的變量延遲在流星

客戶呼叫:

if (Meteor.isClient) { 
 
    Template.front.events({ 
 
    'click #buttondl': function() { 
 
     if (inputdl.value != '') { 
 
     var link = inputdl.value; 
 
     Meteor.call('information', link, function(error, result) { 
 
      if (error) 
 
      console.log(error); 
 
      else 
 
      console.log(result); 
 
     }); 
 
     } 
 
    } 
 
    }); 
 
}

服務器方法:

Meteor.methods({ 
 
    information: function (link) { 
 

 
     exec = Npm.require('child_process').exec; 
 

 
     runCommand = function (error, stdout, stderr) { 
 
      console.log('stdout: ' + stdout); 
 
      console.log('stderr: ' + stderr); 
 

 
      if(error !== null) { 
 
      console.log('exec error: ' + error); 
 
      } 
 
      return stdout; 
 
     } 
 

 
     exec("youtube-dl --get-url " + link, runCommand); 
 
    } 
 
});

回答

1

這個問題每週要問一次。您不能在回調函數中調用返回值。無論是否調用exec的回調,該方法都會在函數結束時返回。這就是異步編程的本質。

您將需要使用exec的同步變體,或以某種其他方式將結果返回給客戶端(例如,被動地更新的集合)。

可以例如使用execSynchttps://nodejs.org/api/child_process.html#child_process_child_process_execsync_command_options):

return execSync("youtube-dl --get-url " + link); 
相關問題