Search code examples
node.jsexpressrequire

Why is my variable undefined when I use "require"?


I have a simple function here to get the git ID (just for testing purposes). I don't understand how to set the variable when evaluating it from top to bottom. It is giving me undefined.

var gitID;
require ('child_process').exec ('git rev-parse HEAD', function (err, stdout) {
  gitID = stdout;
});
console.log (gitID);

How do I set the variable at the top of my js file to be the git ID?


Solution

  • As has been said, it's because the call you're making is an async call using a callback and the console.log(gitID) is completing before the exec operation is able to complete and return the output, hence it is undefined.

    A quick and simple way to solve this is to make use of the promisify util to wrap exec in:

    import { exec } from "child_process";
    import { promisify } from "util";
    
    const promisifiedExec = promisify(exec);
    
    promisifiedExec("git rev-parse HEAD").then(res => console.log(res.stdout));
    

    You can also look at constructing a function to return a promise, there's a lot of information about that in the linked question.