Skip to content

Instantly share code, notes, and snippets.

@wnqueiroz
Created April 15, 2022 01:34
Show Gist options
  • Save wnqueiroz/bdf57a1325556ed9e021212b87504329 to your computer and use it in GitHub Desktop.
Save wnqueiroz/bdf57a1325556ed9e021212b87504329 to your computer and use it in GitHub Desktop.
Custom implementation of how to run UNIX commands through NodeJS
import { exec } from 'child_process'
/**
* Usage:
*
* const stdout = await _`ls -la`;
*
* or:
*
* const flags = [
* "--oneline",
* "--decorate",
* "--color"
* ];
*
* const stdout = await _`git log ${flags}`;
*/
const _ = async (pieces: any, ...args: any): Promise<string> => {
let cmd = pieces[0]
let i = 0
while (i < args.length) {
const arg = Array.isArray(args[i]) ? args[i].join(' ') : args[i]
cmd += arg + pieces[++i]
}
return new Promise((resolve, reject) => {
const spawn = exec(cmd, (error, stdout, stderr) => {
if (error || stderr) reject(error || stderr)
resolve(stdout)
})
spawn.on('exit', (code, signal) => {
code !== 0 &&
reject(
new Error(
`Child process exited with exit code ${code}.${signal ? ` SIGNAL: ${signal}` : ''
}`,
),
)
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment