Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current git branch with node.js

Tags:

git

node.js

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);
    }
});
like image 388
user3438917 Avatar asked Jun 05 '20 23:06

user3438917


3 Answers

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
like image 117
Aayush Mall Avatar answered Nov 21 '22 00:11

Aayush Mall


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.

like image 22
Jake S. Avatar answered Nov 20 '22 23:11

Jake S.


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();
like image 2
jason-warner Avatar answered Nov 21 '22 00:11

jason-warner