首页 > 解决方案 > 使用 node.js 获取当前 git 分支

问题描述

如何在没有外部库的情况下使用 node.js 获取当前的 git 分支?我需要能够获取当前分支名称以在我的节点文件中执行另一个功能。

使用部分工作代码更新

stdout我可以用这个获取分支名称,但如果匹配给定的字符串,似乎无法注销消息。

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);
    }
});

标签: node.jsgit

解决方案


请试试这个作品

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
    }
});

接收输出为

$: node test.js 
The branch is master

推荐阅读