Execute shell commands in Node script

If you are wondering how to execute commands in shell during a node script this is for you. We can achieve this using node’s child_process library.

declare a const for child_process

const exec = require('child_process').exec

Let’s say i want to execute a bunch of git commands like below

git config --global github.user testbot
git config --global user.name "test"
git config --global user.email bot@test.com

I also want to do something else when all of them succeeds. I wrapped a promise around exec and used Promise.all to achieve this.

Promise.all([
    execPromise('git config --global github.user testbot'),
    execPromise('git config --global user.name "test"),
    execPromise('git config --global user.email bot@test.com)
  ])
.then(console.log('git configured successfully'))
.catch(error => validationFailed(error))
function execPromise(cmd){
  console.log(cmd)
  return new Promise(function (resolve, reject) {
    exec(cmd, (error, stdout, stderr) => {
      if (error) {
        reject({cmd: cmd, message: error})
      } else{
        resolve(stdout)
      }
    })
  })
}
function validationFailed (error = {cmd: '', message: ''}) {
  console.warn(`Error occurred while ${error.cmd}:     ${error.message}`)
}

Happy coding!