2014-02-27 41 views
0

我需要使用exec函數以外的變量w1h1的值console.log如何從Node.js中的exec函數獲取變量

exec(command, function(err, stdout, stderr) { 

    var resolution = stdout.split("x"); 
    w1 = resolution[0]; 
    h1 = resolution[1]; 

}); 

console.log(w1 + " - " + h1); 

console.log顯示變量的正確的價值觀,但顯示在此之前的錯誤列表:

ReferenceError: w1 is not defined 
at app.js:30:21 
at callbacks (app/node_modules/express/lib/router/index.js:164:37) 
at param (app/node_modules/express/lib/router/index.js:138:11) 
at pass (app/node_modules/express/lib/router/index.js:145:5) 
at Router._dispatch (app/node_modules/express/lib/router/index.js:173:5) 
at Object.router (app/node_modules/express/lib/router/index.js:33:10) 
at next (app/node_modules/express/node_modules/connect/lib/proto.js:190:15) 
at Object.expressInit [as handle] (app/node_modules/express/lib/middleware.js:30:5) 
at next (app/node_modules/express/node_modules/connect/lib/proto.js:190:15) 
at Object.query [as handle] (app/node_modules/express/node_modules/connect/lib/middleware/query.js:44:5) 

我發現這個類似的問題,但不要爲我工作。 How can we access variable from callback function in node.js?

謝謝。

+0

之前只要定義他們的電話。 'var h1,w1;'然後調用你的'exec'調用。 – Joe

+0

或者在exec內部調用日誌函數,使它們處於範圍之內。 – RacerNerd

+0

但是,要意識到exec是異步的,所以你的console.log會在命令完成之前運行*。你需要在回調中使用console.log。 – bryanmac

回答

1

您這裏有兩個問題:

1期 - 因爲你沒有的功能範圍之外定義的那些變量,它們只範圍內都可用。您需要首先將它們定義爲範圍外的變量 - 當您將它們設置在函數內時,它們將在函數外部可用。

第2期 - 您正試圖在變量設置之前記錄這些變量。當您撥打電話exec時,您傳遞的回調將在exec完成時異步運行。在回調運行之前,腳本將繼續到您的console.log。這意味着無論如何,這些變量將是未定義的,除非您明確定義它們。這使問題1基本沒有意義。

不知道更多關於你的意圖,我覺得這是你應該做的:

exec(command, function(err, stdout, stderr) { 

    var resolution = stdout.split("x"); 
    w1 = resolution[0]; 
    h1 = resolution[1]; 
    console.log(w1 + '-' + h1); 


}); 
相關問題