Get in Touch
Thank you for your interest! Please fill out the form below, and I will do my best to get back to you.

Thank you! Your submission has been received!

Oops! Something went wrong while submitting the form.

Using Git configs in Node.js scripts

Garth Henson
JavaScript, Node.js
31 May 2018

I have been working on a series of CLI and dev tools over the past several months, and I have been trying to figure out the easiest way to come up with default configurations for said tools. One of the ways I have settled on is to assume that the majority of my users will have Git installed on their machine. As such, we should be able to pull name and email address from that configuration at the very least.

With a function like the following, we can retrieve Git configurations for use in our scrips.

How would we use something like this? Well, in my case, I want to prompt the user for some configuration information, but I’d like to default the values to those of their local Git config, since this likely best reflects their preference. I like to use Inquirer.js for this type of thing, and the following snippet shows our function above in use for creating such a prompt.

If you’re going to use a technique like this, one of the keys to remember is that everyone will configure their own environment, so no matter what you think is the gold standard, you always need to fail gracefully. In our case, let’s look at the breakdown of the first function.

First, we make sure we declare the function as async for easy use:

Next, we want to be able to extend this to other attributes as needed, so we use the parallel promise resolver:

Since this takes an array of promises, we will use to build promises for each of the values we wish to retrieve:

Each of our promises executes a git command, so let’s use interpolation to make them easy to read:

Finally, we want to be sure we always return something for our values, even on failure. In this case, a null value is desired when we cannot retrieve from Git. Additionally, we do just a little cleanup of the string, since STDOUT will regularly have trailing newline characters.

At this point, we can be confident we have either retrieved the Git config for both and or a null value for the one(s) that failed. Since we know we are retrieving exactly two values, we can create named variables using destructuring assignment:

This type of leveraging existing system level configuration can save your users immense amounts of time when they are using your tools, so I would strongly encourage you to find the patterns that work best for you.

I hope this is of some help, and as always, feel free to send me any questions or suggestions for improvement!

Garth Henson
Garth is as a lead engineer at The Walt Disney Company, specializing in JavaScript applications.

Recent Blog Posts

Let's Work Together
Contact Me