0

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?

Jake West
  • 99
  • 6
  • The issue isn't `require`. It's that this is an asynchronous operation with a callback and hence the line `gitID = stdout` runs much later than the line `console.log(gitID)`. So at the time you do `console.log(gitID)`, it is still undefined because the `git` process hasn't completed yet, so your callback with `gitID = stdout` inside of it hasn't run yet. – CherryDT Jul 16 '20 at 21:34

1 Answers1

-1

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.

undefined
  • 114
  • 3