Skip to content

Instantly share code, notes, and snippets.

@leonardokl
Last active February 5, 2018 23:33
Show Gist options
  • Save leonardokl/285b0c267d623c6f72044ca612f5133e to your computer and use it in GitHub Desktop.
Save leonardokl/285b0c267d623c6f72044ca612f5133e to your computer and use it in GitHub Desktop.
A function that spawns a new process using the given command, logging the stdout and stderr.
const cp = require('child_process')
/**
* A function that spawns a new process using the given command, logging the stdout and stderr.
*
* @param {String} command
* @param {Array} args
* @return {Promise}
* @example
*
* sh('ping', ['-c', '3', '8.8.8.8'])
* .then(console.log)
* .catch(console.error)
*/
function sh (command, args = []) {
const logString = msg => console.log(`${msg}`)
const childProcess = cp.spawn(command, args)
const formattedArgs = args.length ? ` ${args.join(' ')}` : ''
const params = `$ ${command}${formattedArgs}`
logString(params)
return new Promise((resolve, reject) => {
childProcess.stdout.on('data', logString)
childProcess.stderr.on('data', logString)
childProcess.on('error', reject)
childProcess.on('exit', (code, signal) => {
const message = `Child process exited with code ${code}`
if (code !== 0) {
return reject(new Error(message))
}
return resolve({ code, signal })
})
})
}
module.exports = sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment