Executing shell commands from node.js on Windows

If you’re on Windows and driving node.js through the shell that came with git for windows instead of CMD, it can be surprisingly difficult to invoke shell commands from javascript. The child_process.exec function will always call into CMD.exe instead of bash and if you try to use spawn it will expect you to parse your command into an array as well as escape strings and use backslashes.

It was surprisingly difficult to execute an arbitrary shell command for me so I just wanted to share the small amount of code I ended up writing to achieve it.

Note: this assumes you have Git for Windows or some other shell which you are then running node from.

var spawn = require('child_process').spawn;

function run(cmd, env, callback) {
    if (!cmd) return callback();
    var p = spawn('sh', ['-c', cmd], {
        env: env,
        stdio: 'inherit'
    });
    p.on('close', function (code) {
        if (code !== 0) return callback(new Error('Command failed', code, cmd));
        callback();
    });
}

module.exports = {
    run: run
};

Drop a brain bomb

Please log in using one of these methods to post your comment:

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 )

Google+ photo

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

Connecting to %s