将variables传递给Node.js中的callback

我很新的节点,并试图创build一些获取一些服务器信息。 但是这是我的问题。 我设置了一个configuration对象(这将会及时被发生的事件dynamic更新),然后在一个函数中,我尝试访问这个对象中的一个值。 (见下面的代码)

所以首先,我设置我的变数:

var util = require('util'), child = require('child_process'), config = {}; 

哪个工作可以。 然后我加载我的configuration:

 function loadConfig( ) { // Add some code for auto-loading of args config = { "daemons": [ ["Apache", "apache2"], ["MySQL", "mysqld"], ["SSH", "sshd"] ] }; } 

和调用该函数的init

 loadConfig(); 

之后,我运行我的守护进程检查。

 function getDaemonStatus( ) { for(var i=0; i<config.daemons.length; i++) { child.exec( 'ps ax -o \'%c %P\' | awk \'{if (($2 == 1) && ($1 == "\'' + config.daemons[i][1] + '\'")) print $0}\'', function( error, stdout, stderr ) { console.log(config.daemons[i]); }); } } 

我得到的回应是:

 undefined undefined undefined 

我真的不想使用GLOBALvariables,所以你们可以想办法解决我的问题吗?

谢谢! =]

由于执行的asynchronous顺序,这是很多人遇到的问题。

你的for循环将从0-3看,然后当“i”是4时退出。 这里要记住的难点在于你的execcallback不会立即运行。 一旦进程开始,只有运行,到时候,for循环将完成。

这意味着,基本上,所有三次你的callback函数正在运行,你基本上是这样做的:

 console.log(config.daemons[4]); 

这就是为什么它打印“未定义”。

您需要通过将循环内容封装在一个匿名的自执行函数中来捕获新的作用域中的“i”值。

 function getDaemonStatus( ) { for(var i=0; i<config.daemons.length; i++) { (function(i) { child.exec( 'ps ax -o \'%c %P\' | awk \'{if (($2 == 1) && ($1 == "\'' + config.daemons[i][1] + '\'")) print $0}\'', function( error, stdout, stderr ) { console.log(config.daemons[i]); }); })(i); } } 

另外,我看到你的函数被称为“getDaemonStatus”。 请记住,由于该execcallback是asynchronous的,这也意味着你不能收集每个callback的结果,然后从getDaemonStatus中返回它们。 相反,你将需要传递一个自己的callback,并从你的execcallback中调用它。

更新

请注意,每个迭代都有一个范围的最简单方法是使用forEach ,例如

 function getDaemonStatus( ) { config.daemons.forEach(function(daemon, i){ child.exec( 'ps ax -o \'%c %P\' | awk \'{if (($2 == 1) && ($1 == "\'' + daemon[1] + '\'")) print $0}\'', function( error, stdout, stderr ) { console.log(daemon); }); } }