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.

[code lang=js]
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));

module.exports = {
run: run


Author: justinmchase

I'm a Software Developer from Minnesota.

Leave a Reply

%d bloggers like this: