Javascript 如何从Node.js中的exec函数获取变量
我需要在Javascript 如何从Node.js中的exec函数获取变量,javascript,node.js,express,Javascript,Node.js,Express,我需要在console.log中的exec函数外部使用变量w1和h1的值 exec(command, function(err, stdout, stderr) { var resolution = stdout.split("x"); w1 = resolution[0]; h1 = resolution[1]; }); console.log(w1 + " - " + h1); console.log显示正确的值变量的,但在此之前显示此错误列表: Refe
console.log中的exec
函数外部使用变量w1
和h1
的值
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)
我发现了这个类似的问题,但不适合我。
谢谢。这里有两个问题:
问题1-由于您尚未在函数范围外定义这些变量,因此它们仅在该范围内可用。您需要首先将它们定义为作用域之外的变量-当您在函数内部设置它们时,它们将在函数外部可用
问题2-您试图在设置变量之前记录变量。调用exec
时,传递的是一个回调,该回调将在exec
完成时异步运行。然后,在运行回调之前,脚本将继续运行到控制台.log
。这意味着不管怎样,这些变量都是未定义的,除非您在前面明确定义它们。这使得问题1基本上没有实际意义
在不了解更多你的意图的情况下,我认为这是你应该做的:
exec(command, function(err, stdout, stderr) {
var resolution = stdout.split("x");
w1 = resolution[0];
h1 = resolution[1];
console.log(w1 + '-' + h1);
});
只需在调用之前定义它们<代码>变量h1,w1
然后调用您的exec
调用。或者调用exec中的log函数,使它们在范围内。但是,请认识到exec是异步的,因此您的console.log将在命令完成之前运行。您需要在回调中输入console.log。谢谢,我根据您的回答解决了问题。