Using nodegit, with path_to_repo defined as a string containing the path to the repo you want to get the commit sha for. If you want to use the directory your process is running from, then replace path_to_repo with process.cwd():
var Git = require( 'nodegit' );
Git.Repository.open( path_to_repo ).then( function( repository ) {
return repository.getHeadCommit( );
} ).then( function ( commit ) {
return commit.sha();
} ).then( function ( hash ) {
// use `hash` here
} );
and if you want to manually specify the root directory of the git project, use the second argument of execSync to pass the cwdoption, like execSync('git rev-parse HEAD', {cwd: __dirname})
I was inspired by edin-m's "Solution #2 (no git required)", but I didn't like the substring(5) part which felt like a dangerous assumption. I feel my RegEx is much more tolerant to the variations allowed in git's loose requirements for that file.
The following demo shows that it works for both a checked out branch and a "detached HEAD".