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.

    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){
  return new Promise(function (resolve, reject) {
    exec(cmd, (error, stdout, stderr) => {
      if (error) {
        reject({cmd: cmd, message: error})
      } else{
function validationFailed (error = {cmd: '', message: ''}) {
  console.warn(`Error occurred while ${error.cmd}:     ${error.message}`)

Happy coding!

One thought on “Execute shell commands in Node script

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.