Agneli
Agneli

Reputation: 155

How to get variable from exec function in Node.js

I need to use the value of the variable w1 and h1 outside the exec function, in console.log.

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

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

});

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

The console.log displays the correct values ​​of the variables, but before displays this list of errors:

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)

I found this similar question, but don't work for me. How can we access variable from callback function in node.js?

Thank you.

Upvotes: 1

Views: 2445

Answers (1)

jraede
jraede

Reputation: 6896

You have two issues here:

Issue 1 - because you haven't defined those variables outside of the function scope, they are available only within that scope. You need to first define them as variables outside of the scope - when you set them inside of the function, they will be available outside of the function.

Issue 2 - you are trying to log the variables before they have been set. When you make a call to exec, you are passing a callback that will run asynchronously when the exec finishes. The script will then continue on to your console.log before the callback has been run. That means that no matter what, those variables will be undefined, unless you explicitly define them earlier. This renders issue 1 essentially moot.

Without knowing more about your intentions, I think this is what you should do:

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

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


});

Upvotes: 2

Related Questions