Created
April 15, 2022 01:34
-
-
Save wnqueiroz/bdf57a1325556ed9e021212b87504329 to your computer and use it in GitHub Desktop.
Custom implementation of how to run UNIX commands through NodeJS
This file contains hidden or 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
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