0
我需要使用exec
函數以外的變量w1
和h1
的值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?
謝謝。
之前只要定義他們的電話。 'var h1,w1;'然後調用你的'exec'調用。 – Joe
或者在exec內部調用日誌函數,使它們處於範圍之內。 – RacerNerd
但是,要意識到exec是異步的,所以你的console.log會在命令完成之前運行*。你需要在回調中使用console.log。 – bryanmac