繁体   English   中英

如何从Node.js中的exec函数获取变量

[英]How to get variable from exec function in Node.js

我需要在console.logexec函数之外使用变量w1h1的值。

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)

我发现了类似的问题,但对我不起作用。 我们如何从node.js中的回调函数访问变量?

谢谢。

您在这里有两个问题:

问题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);


});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM