Returning a value from a node child process

One can execute Linux, git shell commands from node script using node’s child process API like exec, execSync. But when you want to save the return value outside of the function scope, one must use execSync. In the below example, we want to get the sha value of the last git commit.

var {execSync} = require("child_process");

function run(cwd, command) {
    return execSync(command, { cwd, encoding: "utf8" });

function getShaHead(cwd) {
    return run(cwd, "git log --oneline -1");

var shaHead = getShaHead();

console.log(shaHead); // ec83f7ce18d4278bb22af2b3773a90a54ddq367a

You may also like...