Created
November 2, 2022 20:51
-
-
Save djhouseknecht/f779755a652985f7c79e1f7874fd82fc to your computer and use it in GitHub Desktop.
Call bash commands from nodeJS and pipe the output to the console/terminal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// use `git-cli` to get the current commit | |
function getCurrentCommit () { | |
return shSync('git rev-parse HEAD').toString().trim() || ''; | |
} | |
async function build() { | |
const currentCommit = getCurrentCommit(); | |
console.log('We are at commit:', currentCommit); | |
console.log('Building our docker image'); // could be any other bash script/command | |
await sh('docker build -t my-image:1.0 .'); | |
console.log('Finished building docker!'); | |
} | |
build(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { spawn, spawnSync } = require('child_process'); | |
const l = console.log; | |
// execSync doesn't return the console output. | |
// `shSync` will return the output once it is complete | |
function shSync (command) { | |
l('$', command); | |
const child = spawnSync( | |
'bash', | |
['-c', command], | |
{ encoding: 'utf8' } | |
); | |
if (child.stdout) { | |
l(child.stdout); | |
} | |
if (child.stderr) { | |
l(child.stderr); | |
} | |
const { status } = child; | |
// l('script completed with code: ' + status); | |
if (status !== 0) { | |
const e = new Error(status); | |
l('Script failed', { | |
command, | |
code: status, | |
stack: e.stack | |
}); | |
process.exit(status); | |
} | |
return child.stdout; | |
} | |
// all output will be logged to console as it happens (unless `shSync`) | |
// execSync does not display the output or errors. | |
async function sh (command) { | |
l('$', command); | |
return new Promise((resolve, reject) => { | |
const child = spawn( | |
'bash', | |
['-c', command], | |
{ encoding: 'utf8' } | |
); | |
child.stdout.on('data', (data) => l(data.toString())); | |
child.stderr.on('data', (data) => l(data.toString())); | |
const e = new Error(); // we want the stack from the original call – not the callback | |
child.on('close', (code) => { | |
// l('script completed with code: ' + code); | |
if (code === 0) { | |
resolve(code); | |
} else { | |
l('Script failed', { | |
command, | |
code, | |
stack: e.stack | |
}); | |
process.exit(code); | |
} | |
}); | |
}); | |
} | |
module.exports = { | |
sh, | |
shSync | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment