-1

I've been battling with this problem for a few hours now, my js code which I am running in node.js is below.

setInterval(function () {
    var exampleVar;
    exec('cat /path/to/unimportant/file', function (error, stdout, stderr) { // This function returns errors, stdout and stderr
        console.log(stdout); // correct value
        exampleVar = stdout;
        console.log(exampleVar); // correct value
    }
    console.log(exampleVar); // undefined
}, unimportantTime);

I would think that because the variable has already been declared by the function exec created's parent scope, that I would be able to assign a value to it. Can someone explain what I'm doing wrong and the correct method for accessing an out of scope variable?

Sheerforce
  • 79
  • 9
  • Just out of curiosity, is it conventional to down vote a question because it has a simple answer that is a hard concept for a beginner to understand? – Sheerforce Jan 02 '16 at 00:20
  • 1
    I don't think there's anything wrong with the question as such, but one reason could be that because a variation of the same question is asked several times every day, some people might get a "oh no, not again" reaction. – JJJ Jan 02 '16 at 00:23
  • It's conventional to downvote common questions ;/ – lleaff Jan 02 '16 at 00:24

1 Answers1

3

Your problem is not one of scope, but of synchronicity.

In Node.js, most functions are asynchronous by default, which means that the execution of your program continues regardless of whether these functions have actually finished running.

So what happens is that your last console.log(exampleVar) executes before the function passed to exec has had time to be executed (as IO operations are typically way slower than executing cached JS code).

See this primer for a more in-depth explanation.

lleaff
  • 4,249
  • 17
  • 23