12

How can I get the current git branch with node.js without an external library? I need to be able to grab the current branch name to perform another function in my node file.

Update with partially working code

I'm able to get the branch name with this, but can't seem to log out a message if the stdout matches the given string.

const { exec } = require('child_process');
exec('git rev-parse --abbrev-ref HEAD', (err, stdout, stderr) => {
    if (stdout === 'name-of-branch') {
        console.log(this is the correct branch);
    }
});
user3438917
  • 417
  • 1
  • 7
  • 26
  • **See Also**: [How to get the current branch name in Git?](https://stackoverflow.com/q/6245570/1366033) – KyleMit Jan 02 '22 at 01:52

4 Answers4

24

Please try this works

const { exec } = require('child_process');
exec('git rev-parse --abbrev-ref HEAD', (err, stdout, stderr) => {
    if (err) {
        // handle your error
    }

    if (typeof stdout === 'string' && (stdout.trim() === 'master')) {
      console.log(`The branch is master`);
      // Call your function here conditionally as per branch
    }
});

Receiving Output as

$: node test.js 
The branch is master
Aayush Mall
  • 963
  • 8
  • 20
13

This should do it:

const { exec } = require('child_process');
exec('git branch --show-current', (err, stdout, stderr) => {
    if (err) {
        // handle your error
    }
});

The stdout variable will contain your branch name. You need to have git installed for this to work.

Jake S.
  • 568
  • 6
  • 25
  • Thanks for the suggestion. I updated my code to get the exact branch, but can't seem to log out a message if the `stdout` matches the string. – user3438917 Jun 06 '20 at 06:22
  • 1
    @user3438917 You probably figured it out by now, but for future refence, you need to call trim() on stdout in order to do that. – Blackness Mar 03 '21 at 13:42
4

Just adding to @Aayush Mall's answer as an ES6 module, so you can fetch the current branch wherever in your project and be used however you like.

import { exec } from 'child_process';

const getBranch = () => new Promise((resolve, reject) => {
    return exec('git rev-parse --abbrev-ref HEAD', (err, stdout, stderr) => {
        if (err)
            reject(`getBranch Error: ${err}`);
        else if (typeof stdout === 'string')
            resolve(stdout.trim());
    });
});

export { getBranch }


// --- --- Another File / Module --- ---

import { getBranch } from './moduleLocation.mjs'

const someAsyncFunction = async () => {
  console.log(await getBranch()); 
}

someAsyncFunction();
  • 1
    The `return` statements can be removed since they don't do anything in the executor. – slikts Sep 20 '21 at 10:36
  • I don't completely agree. I think that being Javascript, the ideal would be to allow a callback and a return if the callback is not passed as a parameter. The discussion would be on the use or not of the return, allowing a more flexible, diversified use of the method in other places of the project. – Rafael Mori Jun 15 '23 at 05:33
0

if, just if, you are indifferent in this strategy of your project, you can remove the external spaces from the string (trim method) and convert it to uppercase or lowercase (toUpperCase or toLowerCase methods) before or inside the conditional.. something like this:

 const stA = ' oOo  ';
 const stB = 'OOO';
 if(stA.trim().toUpperCase() === stB.trim().toUpperCase()) {
    return true;
 } else {
    return false;
 }

Or you can do what @jason-warner says

Rafael Mori
  • 821
  • 9
  • 7