· articles · 2 min read

By Rahul Gupta

Read last git commit in nodejs

Discover efficient methods for retrieving the Git commit ID in Node.js. Compare traditional `child_process` execution against direct file reading from the `.git` directory.

Retrieving the current Git commit ID is a common requirement for Node.js applications, useful for tracking versions, managing deployments, or aiding in debugging. Typically, developers might use Node.js’s child_process module to execute Git commands, a method that, while straightforward, can be relatively slow due to the overhead of process management. This blog post introduces a faster alternative by reading directly from the .git directory, compares its performance with the traditional method, and provides comprehensive code that developers can use in their projects.

Problem Statement

Using the child_process module to retrieve the Git commit ID involves creating a new process for each command execution. This overhead can significantly affect performance, particularly in environments where the commit ID is accessed frequently or needs to be retrieved quickly.

Solutions and Implementation

Below are two methods to retrieve the Git commit ID:

  1. one using the child_process module and
  2. through direct file reading from the .git directory.

Both of these methods are implemented as functions for easy understanding.

const fs = require('fs');
const path = require('path');
const gitDir = path.join(__dirname, '.git'); // Ensure the .git directory is accessible
function readGitHeadFromFile() {
    const headPath = path.join(gitDir, 'HEAD');
    const headContent = fs.readFileSync(headPath, 'utf8').trim();
    if (headContent.startsWith('ref:')) {
        const refPath = headContent.substring(4).trim(); // Get the reference path
        const commitPath = path.join(gitDir, refPath);
        return fs.readFileSync(commitPath, 'utf8').trim(); // Read the commit ID from the reference
    }
    return headContent; // Direct commit in HEAD (not common)
}
const { execSync } = require('child_process');
function readGitHeadUsingChildProcess() {
    return execSync('git rev-parse HEAD').toString().trim();
}

[Top]

Share:
Back to Blog