使用node.js确定是否在git目录中

Kev*_*Bot 7 javascript git bash node.js

我试图确定我的节点进程是否在git目录中运行。可以使用以下方法,但仍在控制台中输出致命错误。

function testForGit() {
    try {
        var test = execSync('git rev-parse --is-inside-work-tree', {encoding: 'utf8'});
    } catch (e) {
    }
    return !!test;
}

console.log(testForGit());
Run Code Online (Sandbox Code Playgroud)

当在git控制下的目录中时,得到true的结果是。但是当在git控制的目录之外时,我得到:

fatal: Not a git repository (or any of the parent directories): .git
false
Run Code Online (Sandbox Code Playgroud)

我的问题:

有没有办法抑制记录的错误?还是有更好的方法来确定我是否在git控制下的目录中?

本质上,我试图做相当于

if git rev-parse --git-dir > /dev/null 2>&1; then
    ... do something
fi
Run Code Online (Sandbox Code Playgroud)

sli*_*wp2 6

如果您在为应用程序构建映像时使用docker并且不想安装git为系统级依赖项。也许是因为我们想要更快地构建图像并保持图像尺寸尽可能小。

@janos 提供的方式是行不通的。

另一种方法是检查.git项目的根路径中是否存在目录。但这取决于您的要求。就我而言,这就足够了。

exports.isGitSync = function isGitSync (dir) {
  return fs.existsSync(path.join(dir, '.git'))
}
Run Code Online (Sandbox Code Playgroud)


Sto*_*ica 1

You can try to redirect stdout inside the execSync call, like this:

var test = execSync('git rev-parse --is-inside-work-tree 2>/dev/null', {encoding: 'utf8'});
Run Code Online (Sandbox Code Playgroud)